# Python – Extract Percentages from String

PythonServer Side ProgrammingProgramming

When it is required to extract the percentages from a string, the regular expressions and the ‘findall’ method of the package is used.

## Example

Below is a demonstration of the same −

import re

my_string = 'Python is % always fun % to learn % and teach'

print("The list is : " )
print(my_string)

my_result = re.findall('\d*%', my_string)

print("The resultant list is : ")
print(my_result)

## Output

The list is :
Python is % always fun % to learn % and teach
The resultant list is :
['%', '%', '%']

## Explanation

• The required packages are imported into the environment.

• A string is defined and is displayed on the console.

• The ‘findall’ method of the regular expression package is used to define a pattern and pass the string to work on it.

• This is assigned to a variable.

• This variable is displayed as the output on the screen.

Published on 13-Sep-2021 11:27:44