Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find strings between two points

Tags:

python

string

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!

like image 242
GoodPie Avatar asked May 14 '13 13:05

GoodPie


People also ask

How do I pull data between two characters in Python?

Given a string and two substrings, write a Python program to extract the string between the found two substrings. In this, we get the indices of both the substrings using index(), then a loop is used to iterate within the index to find the required string between them.


1 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

like image 134
timss Avatar answered Sep 29 '22 00:09

timss