这段代码是用python编写的
我有这个字符串:这段代码是用python编写的,python,regex,string,Python,Regex,String,我有这个字符串: questioncode = YED_q2_a_10 我想检查字符串是否以下划线结尾,然后是int i.e. "_293" 我的尝试: codesplit = questioncode.split('_')[-1] if codesplit.isdigit(): print "true" else: print "false" 正如你所看到的,这并不是我想要的,我相信正则表达式是解决方案 if questioncode.count('_') and q
questioncode = YED_q2_a_10
我想检查字符串是否以下划线结尾,然后是int
i.e. "_293"
我的尝试:
codesplit = questioncode.split('_')[-1]
if codesplit.isdigit():
print "true"
else:
print "false"
正如你所看到的,这并不是我想要的,我相信正则表达式是解决方案
if questioncode.count('_') and questioncode.split('_')[-1].isdigit():
print 'true'
else:
print 'false'
很好(我想说是首选),为什么要使用正则表达式?他们在这里完全没有必要
此语句检查字符串中是否至少有一个下划线,如果有,则拆分字符串,这样您就不会得到超出范围的索引
错误
如果您愿意,您可以按照@qwe的建议,在questioncode中将
questioncode.count(“'u')
)替换为“'u'”。使用re.search()尝试此选项。
import re
if re.match('.*_[0-9]+$', 'YED_q2_a_10'):
print "true"
else
print "false"
\d+
表示有一次或多次出现的任何数字。$
表示字符串的结尾,一个。只需看看是否可以将字符串
转换为int
这是代码。我假设questioncode
中有一个或多个下划线,所以这只在它是下划线时有效
questioncode = "YED_q2_a_10"
codesplit = questioncode.split('_')[-1]
try:
int(codesplit)
print "true"
except ValueError:
print "false"
问题代码中的“代码”比调用.count()
@qwe忘记了美元更有意义。谢谢
questioncode = "YED_q2_a_10"
codesplit = questioncode.split('_')[-1]
try:
int(codesplit)
print "true"
except ValueError:
print "false"