When it is required to extract the percentages from a string, the regular expressions and the ‘findall’ method of the package is used.
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)
The list is : Python is % always fun % to learn % and teach The resultant list is : ['%', '%', '%']
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.