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
test_list = [ 'gf4g' , 'is' , 'best' , '4' , 'gee1ks' ]
print ( "The original list is : " + str (test_list))
res = [sub for sub in test_list if any (ele for ele in sub if ele.isdigit())]
print ( "Strings with any digit : " + str (res))
|
Output
The 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
test_list = [ 'gf4g' , 'is' , 'best' , '4' , 'gee1ks' ]
print ( "The original list is : " + str (test_list))
res = list ( filter ( lambda sub: any (
ele for ele in sub if ele.isdigit()), test_list))
print ( "Strings with any digit : " + str (res))
|
Output
The 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
def fun(s):
digits = "0123456789"
x = s
for i in digits:
s = s.replace(i, "")
if ( len (x) ! = len (s)):
return True
return False
test_list = [ 'gf4g' , 'is' , 'best' , '4' , 'gee1ks' ]
print ( "The original list is : " + str (test_list))
res = []
for i in test_list:
if fun(i):
res.append(i)
print ( "Strings with any digit : " + str (res))
|
Output
The 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
test_list = [ 'gf4g' , 'is' , 'best' , '4' , 'gee1ks' ]
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
print ( "Strings with any digit : " + str (res))
|
Output
The 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
test_list = [ 'gf4g' , 'is' , 'best' , '4' , 'gee1ks' ]
print ( "The original list is : " + str (test_list))
res = [i for i in test_list if re.search( '\d' , i)]
print ( "Strings with any digit : " + str (res))
|
Output
The 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. [GFGTABS] Python li
3 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
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
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
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python. Using str.find() The find() method searches for the first occurrence of the specified substring and retur
3 min read
Extract substrings between brackets - Python
Extract substrings between bracket means identifying and retrieving portions of text that are enclosed within brackets. This can apply to different types of brackets like (), {}, [] or <>, depending on the context. Using regular expressions Regular expressions are the most efficient way to ext
3 min read