您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

当您说[:-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
python 2022/1/1 18:45:10 有323人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶