
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Percentages from String in Python
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.
Advertisements