我在我的应用程序中有这个字符串存储不同的百分比,我想提取百分比值并将其转换为int()。我的字符串看起来像这样......
注意:号码前面会有一个或多个空格。
result ='bFilesystem Size Used Avail Use% Mounted on\n/dev/sda4 30G 20G 8.4G 71% /\n'
percentage = getPercentage(result) #This method should output 71 in this example
print("Percentage is: ", percentage)
提前谢谢。
答案 0 :(得分:4)
您需要一个积极的前瞻 regex
:
import re
result = 'demo percentage is 18%'
percentage = re.search(r'\d+(?=%)', result)
print("Percentage is: ", percentage.group())
# Percentage is: 18
答案 1 :(得分:1)
使用正则表达式:
import re
inp_str = "demo percentage is 18%"
x = re.findall(r'\d+(?=%)', inp_str)
# x is a list of all numbers appeared in the input string
x = [int(i) for i in x]
print(x) # prints - [18]