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