Python – Extract Percentages from String
Given a String, extract all the numbers that are percentages.
Input : test_str = ‘geeksforgeeks 20% is 100% way to get 200% success’ Output : [‘20%’, ‘100%’, ‘200%’] Explanation : 20%, 100% and 200% are percentages present. Input : test_str = ‘geeksforgeeks is way to get success’ Output : [] Explanation : No percentages present.
Method #1 : Using findall() + regex
In this, we employ appropriate regex having “%” symbol in suffix and use findall() to get all occurrences of such numbers from String.
Python3
import re
test_str = 'geeksforgeeks is 100 % way to get 200 % success'
print ( "The original string is : " + str (test_str))
res = re.findall( '\d*%' , test_str)
print ( "The percentages : " + str (res))
|
Output
The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using re.sub() + split()
In this, we perform split of all words, and then from words that have %, we remove all non-numeric strings. This can be buggy in cases, we have different ordering of % and numbers in string.
Python3
import re
test_str = 'geeksforgeeks is 100 % way to get 200 % success'
print ( "The original string is : " + str (test_str))
temp = test_str.split()
res = []
for sub in temp:
if '%' in sub:
res.append(re.sub(r '[^\d, %]' , '', sub))
print ( "The percentages : " + str (res))
|
Output
The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']
Time complexity: O(n), where n is the length of the test_list. The re.sub() + split() takes O(n) time
Auxiliary Space: O(n), extra space of size n is required
Last Updated :
14 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...