Python Checking a string's first and last character
can anyone please explain what is wrong with this code?
str1='"xxx"'
print str1
if str1[:1].startswith('"'):
if str1[:-1].endswith('"'):
print "hi"
else:
print "condition fails"
else:
print "bye"
The output I got is:
Condition fails
but I expected it to print hi
instead.
When you say [:-1]
you are stripping the last element. Instead of slicing the string, you can apply startswith
and endswith
on the string object itself like this
if str1.startswith('"') and str1.endswith('"'):
So the whole program becomes like this
>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
... print "hi"
>>> else:
... print "condition fails"
...
hi
Even simpler, with a conditional expression, like this
>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi
You should either use
if str1[0] == '"' and str1[-1] == '"'
or
if str1.startswith('"') and str1.endswith('"')
but not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for...