Python Checking a string's first and last character

后端 未结 4 1436
南方客
南方客 2020-12-24 10:33

can anyone please explain what is wrong with this code?

str1=\'\"xxx\"\'
print str1
if str1[:1].startswith(\'\"\'):
    if str1[:-1].endswith(\'\"\'):
               


        
4条回答
  •  渐次进展
    2020-12-24 10:46

    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.

提交回复
热议问题