Alex Gordon
Alex Gordon

Reputation: 60761

python: casting to upper and finding string

i am getting stuck on this line:

row[1].upper().find('CELEBREX',1) (this is returning -1)

it seems to not find CELEBREX even though it is there

row[1] = 'celebrex, TRAMADOL'

am i casting to UPPER incorrectly?

Upvotes: 0

Views: 1801

Answers (3)

Tony Veijalainen
Tony Veijalainen

Reputation: 5555

You are starting search from second letter 1 which is e:

row=("",'celebrex, TRAMADOL')
print row[1].upper().find('CELEBREX',1)
print row[1][1:]
"""Output:
-1
elebrex, TRAMADOL
"""

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134891

upper() seems fine, but find doesn't. You want to find at the start of the string (not offset).

row[1].upper().find('CELEBREX')

Upvotes: 2

catchmeifyoutry
catchmeifyoutry

Reputation: 7379

The second argument of find() shouldn't be 1, because it will start search after the first character of the string.

>>> s = 'celebrex, TRAMADOL'
>>> print s.upper().find('CELEBREX')
0

Find() will return 0 because it found the first match at position 0, the first position in the string. So it's important to note that, as you've already discovered, the if find() doesn't find the string, it will return -1. Return value 0 is actually a match.

Upvotes: 4

Related Questions