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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With