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.

For example:

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!

Answers


This is what str.split(delimiter) is for. It returns a list, which you can do [1] or iterate through.

>>> foo = "Hello, this is the string I want, blabla"
>>> foo.split(',')
['Hello', ' this is the string I want', ' blabla']
>>> foo.split(',')[1]
' 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(',')[1].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.

Example:

>>> import re
>>> s = "Hello, This is the string I want, blabla"
>>> re.search(',(.*?),', s).group(1)
' This is the string I want'

Need Your Help

Converting String to Float

iphone ios objective-c

I am attempting to parse a string into an array, take a section of the array at index 1 and convert that string into a float. I have my code here but I am getting the error "Intializing 'float' wit...

TFS label deployment to QA or PROD IIS enviroments

visual-studio tfs build-automation tfsbuild

I am new TFS deployment. Now I have to create automated deployment by giving the label name and environment and its path.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.