Python 检查字符串的首尾字符

79

能否有人解释一下这段代码有什么问题吗?

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

我得到的输出是:

Condition fails

但是我期望它打印的是hi

4个回答

120

当你使用[:-1]时,你正在去除最后一个元素。而不是切片字符串,你可以直接在字符串对象上应用startswithendswith方法,像这样:

if str1.startswith('"') and str1.endswith('"'):

所以整个程序变成了这样

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi

更简单的方法是使用条件表达式,就像这样

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi

33

你应该使用

if str1[0] == '"' and str1[-1] == '"'
或者
if str1.startswith('"') and str1.endswith('"')

但不要同时使用切片和startswith/endswith,否则你将切掉你要查找的内容...


1
你不小心使用了 = 而不是 ==。 - Cody Piersall

16

你正在测试 除最后一个字符外的字符串

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

请注意,最后一个字符"不是切片输出的一部分。

我认为您只是想测试最后一个字符;使用[-1:]来切片获取最后一个元素。

然而,在这里没有必要进行切片操作;直接使用str.startswith()str.endswith()即可。


0

当你设置一个字符串变量时,它不保存引号,因为它们是其定义的一部分。因此,你不需要使用 :1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接