[英]Python Checking a string's first and last character
谁能解释一下这段代码有什么问题?
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]
你正在剥离最后一个元素。 您可以像这样对字符串对象本身应用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
你应该使用
if str1[0] == '"' and str1[-1] == '"'
要么
if str1.startswith('"') and str1.endswith('"')
但不是切片和检查一起开始/结束,否则你将切断你正在寻找的...
您正在测试字符串减去最后一个字符 :
>>> '"xxx"'[:-1]
'"xxx'
注意最后一个字符"
, "
不是切片输出的一部分。
我想你只想测试最后一个角色; 使用[-1:]
切片最后一个元素。
但是,没有必要在这里切片; 只需直接使用str.startswith()
和str.endswith()
。
设置字符串变量时,它不保存它的引号,它们是其定义的一部分。 所以你不需要使用:1
嗨,您也可以试试这个网站 pretagteams.com 来检查 python 中字符串的第一个或最后一个字符<\/a>
myString.charAt(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.