2024-05-19 19:28:26 发布
网友
我有这个字符串:
questioncode = YED_q2_a_10
我想检查字符串是否以下划线结尾,然后是int
i.e. "_293"
我的尝试:
codesplit = questioncode.split('_')[-1] if codesplit.isdigit(): print "true" else: print "false"
正如你所看到的,这不是我想要的,我相信正则表达式是解决方案。你知道吗
import re if re.match('.*_[0-9]+$', 'YED_q2_a_10'): print "true" else print "false"
用re.search()试试这个
re.search()
questioncode = "YED_q2_a_10" if(re.search("_\d+$", questioncode)): print "yes"
\d+表示出现一次或多次的任何数字。$表示字符串的结尾,即anchor。你知道吗
\d+
$
if questioncode.count('_') and questioncode.split('_')[-1].isdigit(): print 'true' else: print 'false'
很好(我想说首选),为什么要使用正则表达式?它们在这里是绝对不必要的。你知道吗
此语句检查字符串中是否至少有一个下划线,如果有,则拆分字符串,这样就不会出现Index out of range错误。你知道吗
Index out of range
如果需要,您可以按照@qwe的建议,用'_' in questioncode替换questioncode.count('_')。你知道吗
'_' in questioncode
questioncode.count('_')
用
re.search()
试试这个\d+
表示出现一次或多次的任何数字。$
表示字符串的结尾,即anchor。你知道吗很好(我想说首选),为什么要使用正则表达式?它们在这里是绝对不必要的。你知道吗
此语句检查字符串中是否至少有一个下划线,如果有,则拆分字符串,这样就不会出现
Index out of range
错误。你知道吗如果需要,您可以按照@qwe的建议,用
'_' in questioncode
替换questioncode.count('_')
。你知道吗相关问题 更多 >
编程相关推荐