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

02 February 2011, 08:29 AM
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..

02 February 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?

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


if wanted in searchText:


import re

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.

02 February 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

02 February 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'] #

02 February 2011, 07:30 AM
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")]

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

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

Gives you a good overview

CGTalk Moderation
02 February 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.