Python检查字符串';第一个也是最后一个字符

Python检查字符串';第一个也是最后一个字符,python,string,python-2.7,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" 我得到的结果是: 条件失败 但是我希望它打印hi。您正在测试的字符串减去最后一个字符: >>> '"x

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

str1='"xxx"'
print str1
if str1[:1].startswith('"'):
    if str1[:-1].endswith('"'):
        print "hi"
    else:
        print "condition fails"
else:
    print "bye"   
我得到的结果是:

条件失败

但是我希望它打印
hi

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

>>> '"xxx"'[:-1]
'"xxx'
请注意最后一个字符,即
,如何不是切片输出的一部分

我认为您只想针对最后一个字符进行测试;使用
[-1:]
仅对最后一个元素进行切片


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

当您说
[:-1]
时,您正在剥离最后一个元素。您可以像这样对字符串对象本身应用
startswith
endswith
,而不是切片字符串

if str1.startswith('"') and str1.endswith('"'):
>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi
所以整个程序变成这样

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi
更简单的是,使用条件表达式,如下所示

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

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

您应该使用

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


但不要将startswith/endswith一起切分并选中,否则您将切掉您要查找的内容…

您无意中使用了=而不是==。