Python检查字符串的第一个和最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19954593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Checking a string's first and last character
提问by Chuvi
can anyone please explain what is wrong with this code?
谁能解释一下这段代码有什么问题?
str1='"xxx"'
print str1
if str1[:1].startswith('"'):
if str1[:-1].endswith('"'):
print "hi"
else:
print "condition fails"
else:
print "bye"
The output I got is:
我得到的输出是:
Condition fails
but I expected it to print hi
instead.
但我希望它会打印出来hi
。
采纳答案by thefourtheye
When you say [:-1]
you are stripping the last element. Instead of slicing the string, you can apply startswith
and endswith
on the string object itself like this
当你说[:-1]
你正在剥离最后一个元素时。您可以像这样在字符串对象本身上应用startswith
和,而不是对字符串进行切片endswith
if str1.startswith('"') and str1.endswith('"'):
So the whole program becomes like this
于是整个程序就变成这样了
>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
... print "hi"
>>> else:
... print "condition fails"
...
hi
Even simpler, with a conditional expression, like this
更简单,用条件表达式,像这样
>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi
回答by Martijn Pieters
You are testing against the string minus the last character:
您正在测试减去最后一个字符的字符串:
>>> '"xxx"'[:-1]
'"xxx'
Note how the last character, the "
, is not part of the output of the slice.
请注意最后一个字符 the"
不是切片输出的一部分。
I think you wanted just to test against the last character; use [-1:]
to slice for just the last element.
我想你只是想测试最后一个字符;使用[-1:]
到切片刚刚过去的元素。
However, there is no need to slice here; just use str.startswith()
and str.endswith()
directly.
但是,这里不需要切片;直接使用str.startswith()
和str.endswith()
。
回答by Farhadix
When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1
当您设置字符串变量时,它不会保存它的引号,它们是其定义的一部分。所以你不需要使用:1
回答by Roberto
You should either use
你应该使用
if str1[0] == '"' and str1[-1] == '"'
or
或者
if str1.startswith('"') and str1.endswith('"')
but not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for...
但不要切片和检查开始/结束一起,否则你会切掉你要找的东西......