Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Extract Percentages from String
When extracting percentages from a string, we use Python's regular expressions module (re) with the findall() method to locate and extract percentage values.
Basic Example with Actual Percentages
Let's extract percentage values from a string containing actual numeric percentages ?
import re
my_string = 'The success rate is 85% and failure rate is 15% with 5% margin error'
print("Original string:")
print(my_string)
# Extract percentages using regex
percentages = re.findall(r'\d+%', my_string)
print("\nExtracted percentages:")
print(percentages)
Original string: The success rate is 85% and failure rate is 15% with 5% margin error Extracted percentages: ['85%', '15%', '5%']
Extract Decimal Percentages
To handle decimal percentages like 12.5%, we modify the regex pattern ?
import re
text = 'Growth was 12.5% last year and 8.75% this quarter'
# Pattern for decimal percentages
decimal_percentages = re.findall(r'\d+\.?\d*%', text)
print("Text:", text)
print("Decimal percentages:", decimal_percentages)
Text: Growth was 12.5% last year and 8.75% this quarter Decimal percentages: ['12.5%', '8.75%']
Extract Only Numeric Values
To get just the numeric values without the % symbol ?
import re
data = 'Scores: 92%, 78%, 85.5%, 91%'
# Extract numbers before % symbol
numbers = re.findall(r'(\d+\.?\d*)%', data)
print("Original data:", data)
print("Numeric values:", numbers)
# Convert to float for calculations
numeric_values = [float(num) for num in numbers]
print("As floats:", numeric_values)
print("Average:", sum(numeric_values) / len(numeric_values))
Original data: Scores: 92%, 78%, 85.5%, 91% Numeric values: ['92', '78', '85.5', '91'] As floats: [92.0, 78.0, 85.5, 91.0] Average: 86.625
Regex Pattern Breakdown
| Pattern | Matches | Example |
|---|---|---|
\d+% |
Integer percentages | 85%, 92% |
\d+\.?\d*% |
Integer and decimal percentages | 85%, 92.5% |
(\d+\.?\d*)% |
Numbers without % symbol | 85, 92.5 |
Conclusion
Use re.findall() with appropriate regex patterns to extract percentages from strings. The pattern \d+\.?\d*% handles both integer and decimal percentages effectively.
Advertisements
