PDA

View Full Version : how .split a string and keep the "splited" part?


mquinta
02-23-2011, 08:29 AM
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:






s_words = 'i need toKeepTHISword'
splitWord = s_words.split('THIS')
# Result: ['i need toKeep', 'word']



Result wanted : ['THIS']


It does not have to be with split function, it can be with whatever other solution may exist..

haggi
02-23-2011, 09:05 AM
Well, if you are splitting by a certain element, you alway know this element, in your case "THIS".
So I suppose you want to do something different. But what exactly? Do you want to split a sequence of characters by upper/lowercase sequences?

Mark-J
02-23-2011, 09:19 AM
So all you're really looking for is validation that THIS is in the string?

wanted='THIS'

if wanted in searchText:
doSomething

or:

import re
if re.search(searchText,wanted):
doSomething

Both of which will run the do function if wanted is in the searchText string, or you just return the initial wanted string. by the way, they're should be a tab before the doSomething, damn formatting on forums.

NaughtyNathan
02-23-2011, 10:13 AM
while I too would probably go with Mark's first suggestion (depending on the exact context) there is also the .find() string method which will give you the character index the given string exists at (or -1 if it's not there)

charIndex = 'i need toKeepTHISword'.find('THIS')
# Result: 13:nathaN

mduvekot
02-23-2011, 03:06 PM
To find uppercase 'words' in a string, you could use something like this:

import re
s_words = 'i need toKeepTHISword'
re.findall('\B[A-Z]{2,}', s_words)
# Result: ['THIS'] #

mquinta
02-24-2011, 07:30 AM
Hi!
Thank you all for your answers!!
Hummm I'll do have to study and understand better the "re" module.. I see that you all used it...

I saw this other method in other forum with the index() function (if you have interest on it):


>>> idx = 'i need toKeepTHISword'.index("THIS")
>>> 'i need toKeepTHISword'[idx:idx+len("THIS")]
'THIS'
>>>



Thanks, I think that with your suggestions I'll be able to continue with the script!

Mark-J
02-24-2011, 09:56 AM
A couple of good links that I often refer back to for the re module:

http://docs.activestate.com/komodo/4.4/regex-intro.html
http://code.google.com/edu/languages/google-python-class/regular-expressions.html

Gives you a good overview

CGTalk Moderation
02-24-2011, 09:56 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.