Saturday, December 28, 2024
Google search engine
HomeLanguagesPython – Retain Numbers in String

Python – Retain Numbers in String

Sometimes, while working with Python Strings, we can have a problem in which we need to perform the removal of all the characters other than integers. This kind of problem can have application in many data domains such as Machine Learning and web development. Let’s discuss certain ways in which this task can be performed.

Input : test_str = ‘G4g is No. 1’ 
Output : 41 

Input : test_str = ‘Gfg is No. 1’ 
Output : 1

Method #1 : Using list comprehension + join() + isdigit() The combination of above functions can be used to solve this problem. In this, we perform the task of extracting integers using isdigit(), list comprehension is used for iteration and join() is used to perform join of numbers filtered. 

Python3




# Python3 code to demonstrate working of
# Retain Numbers in String
# Using list comprehension + join() + isdigit()
 
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
# Using list comprehension + join() + isdigit()
res = "".join([ele for ele in test_str if ele.isdigit()])
 
# printing result
print("String after integer retention : " + str(res))


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time Complexity: O(n), where n is the length of the input string. 
Auxiliary Space: O(n), where n is the length of the input string.

Method #2 : Using regex() The solution of problem can also be found by using regex. In this, we formulate appropriate regex to filter only numbers from string. 

Python3




# Python3 code to demonstrate working of
# Retain Numbers in String
# Using regex()
import re
 
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
# Using regex()
res = re.sub(r'[^\d]+', '', test_str)
 
# printing result
print("String after integer retention : " + str(res))


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Using for loop

Python3




# Python3 code to demonstrate working of
# Retain Numbers in String
 
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
res=""
digits="0123456789"
for i in test_str:
    if i in digits:
        res+=i
 
# printing result
print("String after integer retention : " + str(res))


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(1), as we are using a constant amount of extra space to store the result and the digits string.

Method #4 : Using ord() method

Python3




# Python3 code to demonstrate working of
# Retain Numbers in String
 
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
res=""
for i in test_str:
    if ord(i) in range(48,57):
        res+=i
 
# printing result
print("String after integer retention : " + str(res))


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using re.findall() method. 

Algorithm:

  1. Initialize the input string.
  2. Import the re module.
  3. Use the re.findall() function to find all numeric characters in the string using the regular expression \d.
  4. Use the join() function to concatenate the resulting list of numeric characters into a single string.
  5. Output the resulting string.

Python3




# Python3 code to demonstrate working of
# Retain Numbers in String
# Using regex()
import re
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
# Using regex()
res = ''.join(re.findall(r'\d', test_str))
 
# printing result
print("String after integer retention : " + str(res))


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time Complexity:

The findall() function in re module has a time complexity of O(n), where n is the length of the input string. The join() function has a time complexity of O(m), where m is the number of numeric characters in the input string. Therefore, the time complexity of this algorithm is O(n + m).

Auxiliary Space Complexity:

This algorithm has an auxiliary space complexity of O(m), where m is the number of numeric characters in the input string. This is because the findall() function returns a list of numeric characters, which is then used to construct the resulting string using the join() function. The space complexity is proportional to the number of numeric characters retained in the output.

Method#6: Using enumerate() + join() + isdigit() 

Algorithm:

  1. Initialize the input string test_str.
  2. Print the original string.
  3. Use the enumerate() function to iterate over each character in the string and get its index.
  4. Check if the character at the current index is a digit using the isdigit() function.
  5. If the character is a digit, append it to a list of selected characters.
  6. Use the join() function to combine the selected characters into a string.
  7. Print the resulting string.

Python3




# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
# Using enumerate() + join() + isdigit()
res = "".join([char for idx, char in enumerate(test_str) if char.isdigit()])
 
# printing result
print("String after integer retention : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time complexity:
The time complexity of the algorithm is O(n), where n is the length of the input string. This is because we are iterating over each character in the string once to check if it is a digit.

Auxiliary Space:
The auxiliary space of the algorithm is also O(n), where n is the length of the input string. This is because we are creating a list of selected characters, which can have a maximum size of n, and then joining these characters into a string. However, since the size of the list is at most n, the space complexity of the algorithm is O(n).

Method #7: Using filter() and lambda function

This method involves using the built-in filter() function along with a lambda function to filter out non-numeric characters from the string. 

The filter() function takes two arguments: a function that returns a Boolean value, and an iterable. In this case, we use a lambda function to check if a character is a digit, and the iterable is the string test_str. The filter() function returns an iterator that yields only the elements for which the function returns True. We then use the join() method to join the filtered elements together to form the resulting string.

Python3




# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
# Using filter() and lambda function
res = ''.join(filter(lambda x: x.isdigit(), test_str))
 
# printing result
print("String after integer retention : " + str(res))


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time Complexity: O(n), where n is the length of given test_str
Auxiliary Space: O(n)

Method #8: Using a list comprehension and isnumeric() method.

  • Create a list comprehension to iterate through each character in the string and check if it is numeric using the isnumeric() method: [char for char in test_str if char.isnumeric()]
  • Use the join() method to convert the list of numeric characters back into a string: result = ”.join([char for char in test_str if char.isnumeric()])
  • Print the original string and the resulting string: print(“The original string is : ” + str(test_str)) and print(“String after integer retention : ” + str(result))
     

Python3




# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
# Using list comprehension and isnumeric() method
result = ''.join([char for char in test_str if char.isnumeric()])
 
# printing result
print("String after integer retention : " + str(result))


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.

Method #9: Using map() and filter() functions

Step-by-step approach:

Define a lambda function that takes a character as an argument and returns True if it is a digit, else False.
Apply the lambda function to each character in the string using the map() function.
Filter out the non-digit characters using the filter() function.
Join the remaining digits using the join() function.

Python3




# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Retain Numbers in String
# Using map() and filter() functions
res = "".join(filter(lambda x: x.isdigit(), map(str, test_str)))
 
# printing result
print("String after integer retention : " + str(res))


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time complexity: O(n)
Auxiliary space: O(n), where n is the length of the input string.

Method #10: reduce() function from the functools module

Algorithm:

  1. Import the reduce() function from the functools module.
  2. Initialize a test string test_str and use reduce() to iterate over each character in test_str.
  3. If the character is a digit, append it to the result string x. Otherwise, return x without modifying it.
  4. The initial value of x in reduce() is an empty string ”.
  5. The result is stored in res, So print the string after integer retention based on the value of res.

Python3




from functools import reduce
 
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using reduce() method to retain
# Numbers in String
res = reduce(lambda x, y: x + y if y.isdigit() else x, test_str, '')
 
# printing result
print("String after integer retention : " + str(res))
 
# This code is contributed by Jyothi pinjala.


Output

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time Complexity: The reduce() method and the lambda function inside it runs in linear time complexity O(n), where n is the length of the input string test_str. This is because reduce() applies the lambda function to each character in test_str one by one. The isdigit() method of the string object also runs in constant time complexity O(1), so it does not contribute to the time complexity of this code. Therefore, the time complexity of this code is O(n)

Space Complexity: The space complexity of this code is also O(n), where n is the length of the input string test_str. This is because the size of the result string res is proportional to the number of digits in the input string. Therefore, the space complexity of this code is linear, or O(n).

Method #11:  Using numpy:

Algorithm:

  1. Initialize the input string “test_str”.
  2. Print the original string “test_str”.
  3. Convert the input string to a list of characters.
  4. Check each character in the list if it is a digit or not using numpy.char.isdigit() method.
  5. Filter out the non-numeric characters from the list using numpy.char.array() method.
  6. Join the remaining numeric characters using ”.join() method.
  7. Print the result.

Python3




import numpy as np
 
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using numpy to filter out non-numeric characters
res = ''.join(np.char.array(list(test_str))[np.char.isdigit(list(test_str))])
 
# printing result
print("String after integer retention : " + str(res))
#THis code is contributed by Rayudu.


Output:

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Time complexity: O(n), where n is the length of the input string “test_str”. Converting the string to a list of characters, checking each character if it is a digit or not, and filtering out non-numeric characters using numpy.char.array() and numpy.char.isdigit() methods take O(n) time. Joining the remaining numeric characters using ”.join() method takes O(k) time, where k is the number of numeric characters in the input string.

Space complexity: O(n), where n is the length of the input string “test_str”. The list of characters requires O(n) space and the numpy array of boolean values returned by numpy.char.isdigit() method also requires O(n) space. The remaining variables require constant space.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments