Python Forum
checking if there are numbers in the string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
checking if there are numbers in the string
#11
(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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#12
(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 ! ?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pulling Specifics Words/Numbers from String bigpapa 2 750 May-01-2023, 07:22 PM
Last Post: bigpapa
  How do I check if the first X characters of a string are numbers? FirstBornAlbratross 6 1,521 Apr-12-2023, 10:39 AM
Last Post: jefsummers
  Checking if a string contains all or any elements of a list k1llcod3 1 1,094 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  Find and Replace numbers in String giddyhead 2 1,221 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Finding line numbers starting with certain string Sutsro 3 2,539 Jun-27-2020, 12:36 PM
Last Post: Yoriz
  checking a string for two instances of .. Skaperen 2 1,586 May-13-2020, 09:58 PM
Last Post: Skaperen
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,720 May-09-2019, 12:19 PM
Last Post: Pleiades
  String format checking? MuntyScruntfundle 1 2,430 Mar-06-2019, 12:01 PM
Last Post: buran
  Extract numbers from string ian 1 2,820 Apr-28-2018, 10:40 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020