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

时间:2013-11-13 13:05:20

标签: 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"   

我得到的输出是:

Condition fails

但我希望它能打印hi

4 个答案:

答案 0 :(得分:90)

当你说[:-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

答案 1 :(得分:22)

你应该使用

if str1[0] == '"' and str1[-1] == '"'

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

但不是切片并检查startwith / endswith一起,否则你将切掉你想要的东西......

答案 2 :(得分:15)

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

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

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

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

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

答案 3 :(得分:0)

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

相关问题