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


75

谁能解释这个代码有什么问题吗?

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

我得到的输出是:

Condition fails

但我希望它能打印出来hi

Answers:


115

当您说[:-1]要删除最后一个元素时。您可以像这样对字符串对象本身应用startswith和而不是对字符串进行切片endswith

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('"')

但不要切片并一起检查startwith / endswith,否则您将切出所需内容...


1
您不小心使用=而不是==。
2013年

16

您正在针对字符串减去最后一个字符进行测试:

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

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

我认为您只想对最后一个字符进行测试;使用[-1:]到切片刚刚过去的元素。

但是,这里不需要切片;只需使用str.startswith()str.endswith()直接。


0

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.