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

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

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

我得到的输出是:

 Condition fails 

但我希望它打印hi而不是。

当你说[:-1]你剥夺了最后一个元素。 而不是切分string,你可以像这样在string对象本身上应用startswithendswith

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

所以整个程序就是这样

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

更简单一点,用这样的条件expression式

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

您正在testingstring减去最后一个字符

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

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

我想你只是想对最后一个字符进行testing; 使用[-1:]来分割最后一个元素。

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

你应该使用

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

要么

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

但不切片和检查startswith / endswith在一起,否则你将切片你正在寻找…

当你设置一个stringvariables时,它不保存引号,它们是它定义的一部分。 所以你不需要使用:1