Python - Extract Strings with a digit
Last Updated :
07 Apr, 2023
Given a Strings List, extract those with atleast one digit.
Input : test_list = ['gf4g', 'is', 'best', 'gee1ks']
Output : ['gf4g', 'gee1ks']
Explanation : 4, 1 are respective digits in string.
Input : test_list = ['gf4g', 'is', 'best', 'geeks']
Output : ['gf4g']
Explanation : 4 is digit in string.
Method #1 : Using list comprehension + any() + isdigit()
In this iteration for each string is done using list comprehension, any() and isdigit() is used for task of checking at least one digit.
step by step approach:
- Initialize the input list test_list with some string values.
- Print the original list.
- Create a list comprehension using sub as the loop variable to iterate over each element sub in test_list.
- For each element sub in test_list, use the any() function to check if any character in the string is a digit using the isdigit() method.
- If the above condition is true, append the element sub to the result list res.
- Print the list of strings with digits.
Python3
# Python3 code to demonstrate working of
# Extract Strings with a digit
# Using list comprehension + any() + isdigit()
# initializing list
test_list = ['gf4g', 'is', 'best', '4', 'gee1ks']
# printing original list
print("The original list is : " + str(test_list))
# checking if string contain any string using any()
res = [sub for sub in test_list if any(ele for ele in sub if ele.isdigit())]
# printing result
print("Strings with any digit : " + str(res))
OutputThe original list is : ['gf4g', 'is', 'best', '4', 'gee1ks']
Strings with any digit : ['gf4g', '4', 'gee1ks']
Time Complexity: O(n2)
Space Complexity: O(n)
Method #2 : Using any() + filter() + lambda
In this, we perform task of filtering using lambda and filter(), rest remains the same.
Python3
# Python3 code to demonstrate working of
# Extract Strings with a digit
# Using any() + filter() + lambda
# initializing list
test_list = ['gf4g', 'is', 'best', '4', 'gee1ks']
# printing original list
print("The original list is : " + str(test_list))
# checking if string contain any string using any()
# filter() used to filter strings with digits
res = list(filter(lambda sub: any(
ele for ele in sub if ele.isdigit()), test_list))
# printing result
print("Strings with any digit : " + str(res))
OutputThe original list is : ['gf4g', 'is', 'best', '4', 'gee1ks']
Strings with any digit : ['gf4g', '4', 'gee1ks']
Time Complexity: O(n2)
Space Complexity: O(n)
Method #3 : Without any builtin methods
Python3
# Python3 code to demonstrate working of
# Extract Strings with a digit
def fun(s):
digits = "0123456789"
x = s
for i in digits:
s = s.replace(i, "")
if(len(x) != len(s)):
return True
return False
# initializing list
test_list = ['gf4g', 'is', 'best', '4', 'gee1ks']
# printing original list
print("The original list is : " + str(test_list))
res = []
for i in test_list:
if fun(i):
res.append(i)
# printing result
print("Strings with any digit : " + str(res))
OutputThe original list is : ['gf4g', 'is', 'best', '4', 'gee1ks']
Strings with any digit : ['gf4g', '4', 'gee1ks']
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #4 : Using ord() function
Python3
# Python3 code to demonstrate working of
# Extract Strings with a digit
# initializing list
test_list = ['gf4g', 'is', 'best', '4', 'gee1ks']
# printing original list
print("The original list is : " + str(test_list))
res = []
for i in test_list:
for j in i:
if(ord(j) >= ord('0') and ord(j) <= ord('9')):
res.append(i)
break
# printing result
print("Strings with any digit : " + str(res))
OutputThe original list is : ['gf4g', 'is', 'best', '4', 'gee1ks']
Strings with any digit : ['gf4g', '4', 'gee1ks']
Time Complexity: O(N*M)
Auxiliary Space: O(1)
Method 5 : Using regular expressions
In this approach, we use the re.search() function from the re module which searches for a pattern in the given string. The pattern '\d' represents a digit in the string. The function returns a match object if there is a match and None otherwise. Hence, for every string in the list, we check if there is a digit present by calling re.search('\d', i) where i is the current string in the list. If there is a match, we add the string i to the resultant list. Finally, the resultant list is returned which has all the strings containing at least one digit.
Python3
import re
#initializing list
test_list = ['gf4g', 'is', 'best', '4', 'gee1ks']
#printing original list
print("The original list is : " + str(test_list))
#using re.search() to search for pattern '\d'
#which represents a digit in the string
res = [i for i in test_list if re.search('\d', i)]
#printing result
print("Strings with any digit : " + str(res))
OutputThe original list is : ['gf4g', 'is', 'best', '4', 'gee1ks']
Strings with any digit : ['gf4g', '4', 'gee1ks']
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Python - Extract digits from given string We need to extract the digit from the given string. For example we are given a string s=""abc123def456gh789" we need to extract all the numbers from the string so the output for the given string will become "123456789" In this article we will show different ways to extract digits from a string in Py
2 min read
Python - Extract Tuples with all Numeric Strings Given a list of tuples, extract only those tuples which have all numeric strings. Input : test_list = [("45", "86"), ("Gfg", "1"), ("98", "10")] Output : [('45', '86'), ('98', '10')] Explanation : Only number representing tuples are filtered. Input : test_list = [("Gfg", "1")] Output : [] Explanatio
5 min read
Python - Extract String till Numeric Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as
5 min read
Insert a number in string - Python We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
Python Extract Substring Using Regex Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
2 min read