Best way to find strings between two points
I know this is fairly basic, however I was wondering what the best way to find a string between two referenced points.
finding the string between 2 commas:
Hello, This is the string I want, blabla
My initial thought would be to create a list and have it do something like this:
stringtext=  commacount = 0 word="" for i in "Hello, This is the string I want, blabla": if i == "," and commacount != 1: commacount = 1 elif i == "," and commacount == 1: commacount = 0 if commacount == 1: stringtext.append(i) print stringtext for e in stringtext: word += str(e) print word
However I was wondering if there was an easier way, or perhaps a way that is just simply different. Thankyou!
This is what str.split(delimiter) is for. It returns a list, which you can do  or iterate through.
>>> foo = "Hello, this is the string I want, blabla" >>> foo.split(',') ['Hello', ' this is the string I want', ' blabla'] >>> foo.split(',') ' this is the string I want'
If you want to get rid of the leading space you can use str.lstrip(), or str.strip() to also remove trailing:
>>> foo.split(',').lstrip() 'this is the string I want'
There's usually a built-in method available for something as simple as this in Python :-) For more information check out Built-in Types - String methods
Another option is to find the index of two references when those references doesn't need to be the same (as in two commas):
a = "Hello, This is the string I want, blabla" i = a.find(",") + 1 j = a.find(",",i) a[i:j] >>> ' This is the string I want'
I would use re - that makes it easier if you wish the start/end points to differ, or if you wanted more complicated criteria.
>>> import re >>> s = "Hello, This is the string I want, blabla" >>> re.search(',(.*?),', s).group(1) ' This is the string I want'