Python 检查字符串的第一个和最后一个字符

新手上路,请多包涵

任何人都可以解释这段代码有什么问题吗?

 str1='"xxx"'
print str1
if str1[:1].startswith('"'):
    if str1[:-1].endswith('"'):
        print "hi"
    else:
        print "condition fails"
else:
    print "bye"

我得到的输出是:

 Condition fails

但我希望它打印 hi

原文由 Chuvi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 305
2 个回答

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

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

原文由 thefourtheye 发布,翻译遵循 CC BY-SA 3.0 许可协议

你应该使用

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

要么

if str1.startswith('"') and str1.endswith('"')

但不要切片并检查 startswith/endswith 在一起,否则你会切掉你正在寻找的东西……

原文由 Roberto 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题