1

So, I'm working on a script in Python 3, and I need something like this

control_input=input(prompt_029)
if only string_029 and int in control_input:
    #do something
else:
    #do something else

Basically, I am asking for code that would have condition like this:

if control_input == "[EXACT_string_here] [ANY_integer_here]"

How would the code look like in Python 3?

1

2 Answers 2

2

What you want is to do a regular expression match. Take a look at the re module.

>>> import re
>>> control_input="prompt_029"
>>> if re.match('^prompt_[0-9]+$',control_input):
...     print("Matches Format")
... else:
...     print("Doesn't Match Format")
... 
Matches Format

The regular expression ^prompt_[0-9]+$ matches the following:

^        # The start of the string 
prompt_  # The literal string 'prompt_'
[0-9]+   # One or more digit 
$        # The end of the string 

If the number must contain exactly three digits then you could use ^prompt_[0-9]{3}$ or for a maximum of three then try ^prompt_[0-9]{1,3}$.

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

Comments

0

Without regular expression

>>> myvar = raw_input("input: ")
input: string 1
>>> myvar
'string 1'
>>> string, integer = myvar.strip().split()
>>> "[EXACT_string_here] [ANY_integer_here]" == "{} {}".format(string, integer)
True

1 Comment

This doesn't really do what the OP asked for - the integer part in the input is variable, not constantly 1, and there's no straightforward way to modify your code to allow for that.

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.