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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract Percentages from String 
# Using regex + findall()
import re
  
# initializing strings
test_str = 'geeksforgeeks is 100 % way to get 200 % success'
  
# printing original string
print("The original string is : " + str(test_str))
  
# getting required result from string 
res = re.findall('\d*%', test_str)
  
# printing result 
print("The percentages : " + str(res)) 

chevron_right


Output

The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract Percentages from String 
# Using re.sub() + split()
import re
  
# initializing strings
test_str = 'geeksforgeeks is 100 % way to get 200 % success'
  
# printing original string
print("The original string is : " + str(test_str))
  
# extracting words
temp = test_str.split()
  
# using 
res = []
for sub in temp:
    if '%' in sub:
          
        # replace empty string to all non-number chars
        res.append(re.sub(r'[^\d, %]', '', sub))
  
  
# printing result 
print("The percentages : " + str(res)) 

chevron_right


Output

The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.