Python Checking a string's first and last character

PythonStringPython 2.7

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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...

Solution 3 - Python

You are testing against the string minus the last character:

>>> '"xxx"'[:-1]
'"xxx'

Note how the last character, the ", is not part of the output of the slice.

I think you wanted just to test against the last character; use [-1:] to slice for just the last element.

However, there is no need to slice here; just use str.startswith() and str.endswith() directly.

Solution 4 - Python

When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChuviView Question on Stackoverflow
Solution 1 - PythonthefourtheyeView Answer on Stackoverflow
Solution 2 - PythonRobertoView Answer on Stackoverflow
Solution 3 - PythonMartijn PietersView Answer on Stackoverflow
Solution 4 - PythonFarhadixView Answer on Stackoverflow