ael*_*ath 5 python regex string list-comprehension
我想在特定子字符串之前提取一个数字(“百分比”)
我尝试使用拆分功能
str1="The percentage of success for Team A is around 7.5 per cent. What about their season ?"
print(str1.split("per cent",1)[0])
Run Code Online (Sandbox Code Playgroud)
预期结果: "7.5"
实际结果: "The percentage of success for Team A is around 7.5"
我将介绍 4 种情况:A)仅使用 表示正小数.,B)使用 表示任何小数.,C)使用 表示多个小数,D)使用OR.表示多个小数。.,
A)假设你的浮点数总是以十进制表示
import re
results = re.findall("\d+\.\d+",str1)[0]
print(results)
#'7.5'
Run Code Online (Sandbox Code Playgroud)
B)如果您还有负小数,请使用此(更稳健):
results = re.findall(r"[-+]?\d*\.\d+|\d+",str1)
Run Code Online (Sandbox Code Playgroud)
C)如果您有多个小数,请使用以下命令:
str1="The percentage of success for Team A is around 7.5 per cent and 2.3"
results = re.findall(r"[-+]?\d*\.\d+|\d+",str1)
len(results)
#2 since it found the 2 decimals.
# Use list comprehension to store the detected decimals.
final_results = [i for i in results]
print(final_results)
#['7.5', '2.3']
Run Code Online (Sandbox Code Playgroud)
D)最后,如果小数用.(点)或,(逗号)表示,则使用超级稳健:
str1="The percentage of success for Team A is around 7.5 per cent and 2,3"
results = re.findall(r"\d+[.,]*\d*[.,]*\d*",str1)
final_results = [i for i in results]
#['7.5', '2,3']
Run Code Online (Sandbox Code Playgroud)