By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,898 Members | 1,198 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,898 IT Pros & Developers. It's quick & easy.

How to split a string and keep the delimiter

P: 4
Hi!
So I have a string that I want to split but I need to keep the exact part that I'm splitting

for example
Expand|Select|Wrap|Line Numbers
  1.  
  2. s_words = 'i need toKeepTHISword'
  3.  
  4. splitWord = s_words.split('THIS')
  5.  
  6. # Result: ['i need toKeep', 'word']
  7.  
  8.  

Result wanted:

['THIS']




Thanks in advance!
Feb 23 '11 #1

✓ answered by bvdet

Use string method index() and slicing.
Expand|Select|Wrap|Line Numbers
  1. >>> idx = 'i need toKeepTHISword'.index("THIS")
  2. >>> 'i need toKeepTHISword'[idx:idx+len("THIS")]
  3. 'THIS'
  4. >>> 

Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Use string method index() and slicing.
Expand|Select|Wrap|Line Numbers
  1. >>> idx = 'i need toKeepTHISword'.index("THIS")
  2. >>> 'i need toKeepTHISword'[idx:idx+len("THIS")]
  3. 'THIS'
  4. >>> 
Feb 23 '11 #2

Rabbit
Expert Mod 10K+
P: 12,383
Or just append THIS to every item except the last item. Since it must necessarily end with the delimiter.
Feb 23 '11 #3

P: 4
Thank you both!
I'll take a more careful look to the index() method, but with that lines the script works just fine :)
Feb 24 '11 #4

Post your reply

Sign in to post your reply or Sign up for a free account.