Python 在特定子字符串前提取一个十进制数

标签 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])

预期结果:“7.5”

实际结果:“A 队的成功率约为 7.5”

最佳答案

你可以使用 str.index要找到 percent 所在的索引,将字符串切片到结果索引,然后 rstripsplit 保留最后一个元素结果列表:

str1[:str1.index('per cent')].rstrip().split()[-1]
# '7.5'

关于Python 在特定子字符串前提取一个十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56883547/

相关文章:

python - 在 timeit 中使用分号

python - 如何获得适用于 Windows 的 python-dev?

regex - HTML 5 的 24 小时时间正则表达式

c# - 如何根据点获取字符串的子代

c++ - 删除字符串中的一个字符

python - 使用 pytest 报告单个函数的多个测试

python - 将 networkx 2D 图转换为 3D 交互式图

regex - 在 .htaccess 中从 URL 中删除单词

python - 正则表达式,先查找 - Python

java - 将多行读入Java中的扫描仪对象