我想在特定子字符串(“百分比”)之前提取一个数字
我尝试使用拆分功能
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
所在的索引,将字符串切片到结果索引,然后 rstrip
和 split
保留最后一个元素结果列表:
str1[:str1.index('per cent')].rstrip().split()[-1]
# '7.5'
关于Python 在特定子字符串前提取一个十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56883547/