5

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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Scout721
  • 91
  • 1
  • 3
  • 8

2 Answers2

2

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)
Paluter
  • 73
  • 7
0

I would use the find method.

start_pt = temp.find("\"")
end_pt = temp.find("\"", start_pt + 1)  # add one to skip the opening "
quote = temp[start_pt + 1: end_pt]

>>> print start_pt, end_pt, quote
10, 16, 'leave'
Shaido
  • 27,497
  • 23
  • 70
  • 73
af3ld
  • 782
  • 8
  • 30