PDA

View Full Version : Python - Get a substring from between two characters



ironfistchamp
February 3rd, 2007, 08:25 PM
Hey all

I would like to know how I could get s substring from between two characters. For example



# my first string
myString = "Hello there !bob@"

#my sub string
subString = #whatever i need to do here to return JUST bob



If anyone could help me get this I'd be really happy.

Thanks

Ironfistchamp

phansiizwe
February 3rd, 2007, 08:40 PM
myString[myString.find("!")+1:myString.find("@")]

ironfistchamp
February 3rd, 2007, 08:47 PM
Thanks for the reply but this produces the output:



File "subsearch.py", line 2
myString=[myString.find("!")+1:myString.find("@")]
^
SyntaxError: invalid syntax


Here is the code I used



myString="Hello there !bob@"
myString=[myString.find("!")+1:myString.find("@")]
print myString


What am I doing wrong?

Thanks

Ironfistchamp

phansiizwe
February 3rd, 2007, 08:53 PM
Do it like:


myString="Hello there !bob@"
mySubString=myString[myString.find("!")+1:myString.find("@")]
print mySubString

the [] are indices to the string myString, e.g. myString[0:5] will return the first 5 characters of your string.

ironfistchamp
February 3rd, 2007, 08:58 PM
Awesome thanks so much that is brilliant.

Ironfistchamp

rajohns08
February 16th, 2011, 09:34 PM
Do it like:


myString="Hello there !bob@"
mySubString=myString[myString.find("!")+1:myString.find("@")]
print mySubString

the [] are indices to the string myString, e.g. myString[0:5] will return the first 5 characters of your string.


what if im searching a html chat log file and i want to return everything that a single person has said. so i would want to return what is between "nameofperson" and "endoftheirsentence" for everytime it occurs. i know the find function finds the first index of what you search for. but is there a way to use this function to move on to the next index after you have found the first one? so that you can "find next" basically?

wmcbrine
February 16th, 2011, 11:44 PM
You probably should be looking at the "re" module.

kurum!
February 17th, 2011, 03:05 AM
You probably should be looking at the "re" module.

no need to call a module just to do that.



for s in mystring.split("endoftheirsentence"):
if "nameofperson" in s:
print s.split("nameofperson")[-1]

cariboo
February 17th, 2011, 05:44 AM
This thread is 3 years old, I'd suggest you start a new thread with a link to this one. Closed.