jurd jurd - 1 year ago 71
Python Question

Python - How to query a "s%d" whilst checking if %d is within list length?

I am reading a user input which must be a character and a integer within a limit.
Let's say I have a list 's' of size 3, then the user input must be "s%d" where %d must be 1, 2, or 3. The size can vary, so using:

choice == "s1" or choice == "s2" or ...
would not work.

Here is what I have:

num = [range(1, len(input) + 1)]
if choice == "s%d" %d in num:

I've tried a few options and python3 functions, but I can't seem to get it to work.
Let me know if I should provide more info.

** "s1" must be entered as a whole string, it cannot be separated.

Answer Source

Just check if the number from the user input is in your list len range, u can do:

num = [range(1, len(input) + 1)]
choice = input("Enter 's' followed by a number: ")
if int(choice[1:]) > len(l): # It will work if indeed the single
    <do something>           # letter is followed by an int.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download