谁能解释这个代码有什么问题吗?
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:
当您说[:-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