Python Forum

Full Version: checking if there are numbers in the string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(Apr-05-2017, 10:14 PM)Ofnuts Wrote: [ -> ]A different way of doing it:

Python Code: (Double-click to select all)
1
len(flyTo)!=len(flyTo.translate(None,'0123456789'))
This will not work iin Pyton 3
(Apr-05-2017, 08:17 PM)Sp00f Wrote: [ -> ]can you elaborate on, "any(c.isdigit() for c in flyTo):"
Ofnuts already explained it and also provided alternative. mine and his are universal - i.e. they will check that there is at least one digit in a string and don't depend on anything.
Here is another alternative:

flyTo = input("Where would you like to fly? ")
if flyTo.isalpha():
  print("Okay, we are going to {} ".format(flyTo))
elif flyTo.isalnum():
  print("You accidentally added a number")
else:
  print("??")
That one however depends on the previous check - i.e. from flyTo.isalpha() being False we already know that our string does not contain ONLY letters. Only then we check if it contains letters AND/OR digits.
To make it more clear see this:
>>> 'ab'.isalnum()
True
>>> 'ab1'.isalnum()
True
i.e. if isalnum is True, our string MAY contain digits but that is not 100% certain - it MAY as well contain only letters.

Finally, as I already said - it's best to drop the elif clause altogether. What difference does it make if user by accident has entered 1 or ! ?
Pages: 1 2