0

I have this string:

questioncode = YED_q2_a_10

I want to check if the string ends with an underscore then an int

i.e. "_293" 

My attempt:

codesplit = questioncode.split('_')[-1]

if codesplit.isdigit():
    print "true"
else:
    print "false"

as you can see this is not doing what I want and I believe regex is the solution.

0

4 Answers 4

2
if questioncode.count('_') and questioncode.split('_')[-1].isdigit():
    print 'true'
else:
    print 'false'

is perfectly fine (and I'd say preferred), why do you want to use regular expressions? They're absolutely unnecessary here.

This statements check if there's at least one underscore in the string and splits the string if yes, so you won't get Index out of range error.

If you want you can replace questioncode.count('_') with '_' in questioncode, as suggested by @qwe.

Sign up to request clarification or add additional context in comments.

1 Comment

'_' in questioncode makes more sense than calling .count().
0

Try this one using re.search()

questioncode = "YED_q2_a_10"
if(re.search("_\d+$", questioncode)):
    print "yes"

\d+ means any digit having one or more occurrence. And $ means the end of the string, an anchor.

Comments

0
import re

if re.match('.*_[0-9]+$', 'YED_q2_a_10'):
    print "true"
else
    print "false"

Comments

0

Simply see if you can convert string to int.

Here is the code. I assume there are one or more underscore in questioncode, so this only works when it is.

questioncode = "YED_q2_a_10"
codesplit = questioncode.split('_')[-1]

try:
    int(codesplit)
    print "true"
except ValueError:
    print "false"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.