Let's say I have a String variable
temp = 'I need to "leave" this place'
How would I be able to use temp.index() to find where the quotes("") begin and end?
Let's say I have a String variable
temp = 'I need to "leave" this place'
How would I be able to use temp.index() to find where the quotes("") begin and end?
Note: As said in the other answer, I would advise you to use the find(substring)
function. To my knowledge both index
and find
work equally well, but if you use index(substring)
, you will have to handle the possible ValueError
exception if substring
is not found.
So to find where the quotes begin and end, you would do the following:
First, find where the first quote is (i.e. where the quotes begin):
startIndex = temp.find('\"')
Now we need to know if the string even had any quote to begin with. The find(substring)
function will return -1
if substring
is not found. If substring
was found, then let's find the index of the second quote. If that second quote is found, then lets print out the start and end indices of the quotes.
if startIndex != -1: #i.e. if the first quote was found
endIndex = temp.find('\"', startIndex + 1)
if startIndex != -1 and endIndex != -1: #i.e. both quotes were found
print 'Start: ' + str(startIndex)
print 'End: ' + str(endIndex)