Python检查字符串的第一个和最后一个字符 [英] Python Checking a string's first and last character
本文介绍了Python检查字符串的第一个和最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能解释一下这段代码有什么问题?
str1='"xxx"'打印 str1如果 str1[:1].startswith('"'):如果 str1[:-1].endswith('"'):打印嗨"别的:打印条件失败"别的:打印再见"
我得到的输出是:
条件失败
但我希望它改为打印 hi
.
解决方案
当你说 [:-1]
时,你正在剥离最后一个元素.您可以像这样在字符串对象本身上应用 startswith
和 endswith
而不是切片字符串
如果 str1.startswith('"') 和 str1.endswith('"'):
所以整个程序就变成这样了
<预><代码>>>>str1 = '"xxx"'>>>如果 str1.startswith('"') 和 str1.endswith('"'):...打印嗨">>>别的:...打印条件失败"...你好更简单,有条件表达式,像这样
<预><代码>>>>print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")你好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.
解决方案
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
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
这篇关于Python检查字符串的第一个和最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文