- Python: if a word contains a digit
- 6 Answers 6
- Code Break Down
- This is how the code works
- How do you check in python whether a string contains only numbers?
- 12 Answers 12
- Python string contains any digit
- # Table of Contents
- # Check if a string contains a number in Python
- # Check if a string contains a number using a for loop
- # Check if a string contains a number using re.search()
- # Check if a string contains a number using re.findall()
- # Check if a string contains only Numbers in Python
- # Check if a string contains only Numbers using re.match()
Python: if a word contains a digit
I’m writing a function that will take a word as a parameter and will look at each character and if there is a number in the word, it will return the word This is my string that I will iterate through ‘Let us look at pg11.’ and I want to look at each character in each word and if there is a digit in the word, I want to return the word just the way it is.
import string def containsDigit(word): for ch in word: if ch == string.digits return word
6 Answers 6
if any(ch.isdigit() for ch in word): print word, 'contains a digit'
To make your code work use the in keyword (which will check if an item is in a sequence), add a colon after your if statement, and indent your return statement.
import string def containsDigit(word): for ch in word: if ch in string.digits: return word
>>> import re >>> word = "super1" >>> if re.search("\d", word): . print("y") . y >>>
So, in your function, just do:
import re def containsDigit(word): if re.search("\d", word): return word print(containsDigit("super1"))
@»why not use regex?» -> because regex is the wrong tool for everything, except for things that only regex can do.
I think that iCodez is trying to say that there’s no need to use a Bazooka when a rifle works just fine. (To be explicit: bazooka==regex, rifle==python’s string methods).
for ch in word: if ch.isdigit(): #
Often when you want to know if "something" contains "something_else" sets may be usefull.
digits = set('0123456789') def containsDigit(word): if set(word) & digits: return word print containsDigit('hello')
If you desperately want to use the string module. Here is the code:
import string def search(raw_string): for raw_array in string.digits: for listed_digits in raw_array: if listed_digits in raw_string: return True return False
If I run it in the shell here I get the wanted resuts. (True if contains. False if not)
>>> search("Give me 2 eggs") True >>> search("Sorry, I don't have any eggs.") False
Code Break Down
This is how the code works
The string.digits is a string. If we loop through that string we get a list of the parent string broke down into pieces. Then we get a list containing every character in a string with'n a list. So, we have every single characters in the string! Now we loop over it again! Producing strings which we can see if the string given contains a digit because every single line of code inside the loop takes a step, changing the string we looped through. So, that means ever single line in the loop gets executed every time the variable changes. So, when we get to; for example 5. It agains execute the code but the variable in the loop is now changed to 5. It runs it agin and again and again until it finally got to the end of the string.
How do you check in python whether a string contains only numbers?
How do you check whether a string contains only numbers? I've given it a go here. I'd like to see the simplest way to accomplish this.
import string def main(): isbn = input("Enter your 10 digit ISBN number: ") if len(isbn) == 10 and string.digits == True: print ("Works") else: print("Error, 10 digit number was not inputted and/or letters were inputted.") main() if __name__ == "__main__": main() input("Press enter to exit: ")
Except the answers below, a "Non Pythonic" way is if [x for x in isbn if x in '0123456789']; that you can extend if the user put separators in isbn - add them to list
I recommend using regex if you are reading ISBN numbers. ISBNs can be either 10 or 13 digits long, and have additional restrictions. There is a good list of regex commands for matching them here: regexlib.com/… Many of these will also let you correctly read the ISBN hyphens, which will make it easier for people to copy and paste.
@Kevin And, while 13-digit ISBNs are indeed digits only, 10-digit ISBNs can have X as the final character.
12 Answers 12
You'll want to use the isdigit method on your str object:
if len(isbn) == 10 and isbn.isdigit():
str.isdigit()
Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
Python string contains any digit
Last updated: Jan 25, 2023
Reading time · 5 min
# Table of Contents
# Check if a string contains a number in Python
To check if a string contains a number in Python:
- Use a generator expression to iterate over the string.
- Use the str.isdigit() method to check if each char is a digit.
- Pass the result to the any() function.
- The any function will return True if the string contains a number.
Copied!def contains_number(string): return any(char.isdigit() for char in string) print(contains_number('abc123')) # 👉️ True print(contains_number('abc')) # 👉️ False print(contains_number('-1abc')) # 👉️ True if contains_number('abc123'): # 👇️ this runs print('The string contains a number') else: print('The string does NOT contain a number') # ----------------------------- # ✅ check if a string contains a specific number print('123' in 'abc123') # 👉️ true print('567' in 'abc123') # 👉️ False
We used a generator expression to iterate over the string.
Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we use the str.isdigit() method to check if the character is a digit.
The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.
The last step is to pass the generator object to the any() function.
Copied!def contains_number(string): return any(char.isdigit() for char in string) print(contains_number('abc123')) # 👉️ True print(contains_number('abc')) # 👉️ False print(contains_number('-1abc')) # 👉️ True
The any function takes an iterable as an argument and returns True if any element of the iterable is truthy.
If you need to check if a string contains a specific number, use the in operator.
Copied!print('123' in 'abc123') # 👉️ True print('567' in 'abc123') # 👉️ False
The in operator tests for membership. For example, x in s evaluates to True if x is a member of s , otherwise it evaluates to False .
# Check if a string contains a number using a for loop
You can also use a for loop to check if a string contains a number.
Copied!def contains_number(string): for char in string: if char.isdigit(): return True return False print(contains_number('abc123')) # 👉️ True print(contains_number('abc')) # 👉️ False print(contains_number('-1abc')) # 👉️ True if contains_number('abc123'): # 👇️ this runs print('The string contains a number') else: print('The string does NOT contain a number')
The for loop iterates over the string and checks if each character is a number using the isdigit() method.
# Check if a string contains a number using re.search()
This is a two-step process:
- Use the re.search() method to check if the string contains any digits.
- Use the bool() class to convert the output from re.search to a boolean.
Copied!import re def contains_number(string): return bool(re.search(r'\d', string)) print(contains_number('abc123')) # 👉️ True print(contains_number('abc')) # 👉️ False print(contains_number('-1abc')) # 👉️ True
The re.search method looks for the first location in the string where the provided regular expression produces a match.
If the re.search() method finds any digits, it will return a match object, otherwise None is returned.
The first argument we passed to the method is a regular expression.
The \d character matches the digits 1 (and many other digit characters).
If the string contains any digits, the re.search method will return a match object, which when converted to boolean returns True .
Copied!# 👇️ print(re.search(r'\d', 'abc123')) # 👇️ None print(re.search(r'\d', 'abc'))
If the pattern is not matched in the string, the method returns None, which is a falsy value.
An alternative to using the \d character is to specify a set of digits 8 .
Copied!import re def contains_number(string): return bool(re.search(r'4', string)) print(contains_number('abc123')) # 👉️ True print(contains_number('abc')) # 👉️ False print(contains_number('-1abc')) # 👉️ True
The square [] brackets are used to indicate a set of characters.
In the case of 1 , the pattern matches any digit.
# Check if a string contains a number using re.findall()
Alternatively, you can use the re.findall() method.
Copied!import re my_str = 'a12b34c56' matches = re.findall(r'\d+', my_str) print(matches) # 👉️ ['12', '34', '56'] if len(matches) > 0: print('The string contains a numebr') else: print('The string does NOT contain a number')
The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.
If the list of matches has a length greater than 0 , then the string contains at least 1 number.
# Check if a string contains only Numbers in Python
You can use the str.isnumeric() method to check if a string contains only numbers.
Copied!import re my_str = '3468910' print(my_str.isnumeric()) # 👉️ True if my_str.isnumeric(): # 👇️ This runs print('The string contains only numbers') else: print('The string does NOT contain only numbers')
The str.isnumeric method returns True if all characters in the string are numeric, and there is at least one character, otherwise False is returned.
Copied!print('5'.isnumeric()) # 👉️ True print('50'.isnumeric()) # 👉️ True print('-50'.isnumeric()) # 👉️ False print('3.14'.isnumeric()) # 👉️ False print('A'.isnumeric()) # 👉️ False
Notice that the str.isnumeric() method returns False for negative numbers (they contain a minus) and for floats (they contain a period).
Use a try/except statement if you need to check if a string is a valid integer or a valid floating-point number.
Copied!# ✅ Check if a string is a valid integer def is_integer(string): try: int(string) except ValueError: return False return True print(is_integer('359')) # 👉️ True print(is_integer('-359')) # 👉️ True print(is_integer('3.59')) # 👉️ False print(is_integer('3x5')) # 👉️ False # ---------------------------------------------- # ✅ Check if a string is a valid float def is_float(string): try: float(string) except ValueError: return False return True print(is_float('359')) # 👉️ True print(is_float('-359')) # 👉️ True print(is_float('3.59')) # 👉️ True print(is_float('3x5')) # 👉️ False
If converting the string to an integer or float fails, the except block runs where we handle the ValueError by returning False from the function.
# Check if a string contains only Numbers using re.match()
Alternatively, you can use the re.match() method.
The re.match() method will return a match object if the string contains only numbers, otherwise None is returned.
Copied!import re def only_numbers(string): return re.match(r'^1+$', string) # 👇️ print(only_numbers('3590')) if only_numbers('3590'): # 👇️ this runs print('The string contains only numbers') else: print('The string does NOT contain only numbers')
The re.match method returns a match object if the provided regular expression is matched in the string.
The match() method returns None if the string doesn't match the regex pattern.
The first argument we passed to the re.match() method is a regular expression.
Copied!import re def only_numbers(string): return re.match(r'^3+$', string)
The square brackets [] are used to indicate a set of characters.
The 0-9 characters match the digits in the range.