Python – 从字符串中提取百分比
给定一个字符串,提取所有百分比的数字。
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.
方法 #1:使用 findall() + 正则表达式
在此,我们使用适当的正则表达式,在后缀中带有“%”符号,并使用 findall() 从 String 中获取所有出现的此类数字。
Python3
# 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))
Python3
# 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))
输出
The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']
方法#2:使用 re.sub() + split()
在此,我们对所有单词进行拆分,然后从具有 % 的单词中删除所有非数字字符串。在某些情况下,这可能是错误的,我们在字符串中有不同的 % 和 numbers 排序。
Python3
# 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))
输出
The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']