Python检查字符串的第一个和最后一个字符

Chu*_*uvi 63 python string python-2.7

任何人都可以解释这个代码有什么问题吗?

str1='"xxx"'
print str1
if str1[:1].startswith('"'):
    if str1[:-1].endswith('"'):
        print "hi"
    else:
        print "condition fails"
else:
    print "bye"   
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

Condition fails
Run Code Online (Sandbox Code Playgroud)

但我希望它能打印出来hi.

the*_*eye 99

当你说[:-1]你正在剥离最后一个元素时.相反,切片串的,你可以申请startswith并endswith在String对象本身这样的

if str1.startswith('"') and str1.endswith('"'):
Run Code Online (Sandbox Code Playgroud)

所以整个程序就像这样

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi
Run Code Online (Sandbox Code Playgroud)

更简单,使用条件表达式,就像这样

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi
Run Code Online (Sandbox Code Playgroud)


Rob*_*rto 27

你应该使用

if str1[0] == '"' and str1[-1] == '"'
Run Code Online (Sandbox Code Playgroud)

要么

if str1.startswith('"') and str1.endswith('"')
Run Code Online (Sandbox Code Playgroud)

但不是切片和检查一起开始/结束,否则你将切断你正在寻找的...


Mar*_*ers 15

您正在测试字符串减去最后一个字符:

>>> '"xxx"'[:-1]
'"xxx'
Run Code Online (Sandbox Code Playgroud)

注意最后一个字符如何"不是切片输出的一部分.

我想你只想测试最后一个角色; 用于[-1:]切片最后一个元素.

但是,没有必要在这里切片; 只需使用str.startswith()和str.endswith()直接.