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 Strings with only Alphabets
In Python, extracting strings that contain only alphabetic characters involves filtering out any strings that include numbers or special characters. The most efficient way to achieve this is by using the isalpha() method, which checks if all characters in a string are alphabetic.Pythonli= ['gfg', 'i
2 min read
Python - Extract date in String
Given a string, the task is to write a Python program to extract date from it. Input : test_str = "gfg at 2021-01-04" Output : 2021-01-04 Explanation : Date format string found. Input : test_str = "2021-01-04 for gfg" Output : 2021-01-04 Explanation : Date format string found. Method #1 : Using re.s
4 min read
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
Integer to Binary String in Python
We have an Integer and we need to convert the integer to binary string and print as a result. In this article, we will see how we can convert the integer into binary string using some generally used methods.Example: Input : 77Output : 0b1001101Explanation: Here, we have integer 77 which we converted
4 min read
Iterate over words of a String in Python
In this article, weâll explore different ways to iterate over the words in a string using Python.Let's start with an example to iterate over words in a Python string:Pythons = "Learning Python is fun" for word in s.split(): print(word)OutputLearning Python is fun Explanation: Split the string into w
2 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 string between two substrings
The problem is to extract the portion of a string that lies between two specified substrings. For example, in the string "Hello [World]!", if the substrings are "[" and "]", the goal is to extract "World".If the starting or ending substring is missing, handle the case appropriately (e.g., return an
3 min read
Python - Word starting at Index
Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let's discuss certain ways in which this task can be performed. Method #1: Using a loop This is a bru
2 min read