如何在python中提取部分字符串(字符串长度可能不同)

如何在python中提取部分字符串(字符串长度可能不同),python,string,Python,String,我的应用程序中有一个存储不同百分比的字符串,我只想提取百分比值并将其转换为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("Perc

我的应用程序中有一个存储不同百分比的字符串,我只想提取百分比值并将其转换为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)

提前感谢。

使用正则表达式:

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]

使用正则表达式:

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]

您需要一个正向前瞻
regex

import re

result = 'demo percentage is   18%'
percentage = re.search(r'\d+(?=%)', result)        
print("Percentage is: ", percentage.group())

# Percentage is:  18

您需要一个正向前瞻
regex

import re

result = 'demo percentage is   18%'
percentage = re.search(r'\d+(?=%)', result)        
print("Percentage is: ", percentage.group())

# Percentage is:  18

是不是总是这样?然后你可以使用一个简单的分割函数,它总是这样吗?然后您可以使用一个简单的拆分函数。这不适用于
inp\u str=“demo 11百分比为18%”
。是的,我知道我的解决方案不会处理上述情况,但问题不仅仅是提取
%
符号前面的数字。无论如何,我已经更新了答案。result='bFilesystem Size Used Avail Use%Mounted on\n/dev/sda4 30G 20G 8.4G 71%/\n'这是我要使用的字符串precise@ManojJahgirdar请从下一次开始准确说明您的要求:)@WasiAhmad是的,很抱歉给您带来不便。谢谢……)这不适用于
inp_str=“demo 11百分比为18%”
。是的,我知道我的解决方案不会处理上述情况,但问题不仅仅是提取
%
符号前面的数字。无论如何,我已经更新了答案。result='bFilesystem Size Used Avail Use%Mounted on\n/dev/sda4 30G 20G 8.4G 71%/\n'这是我要使用的字符串precise@ManojJahgirdar请从下一次开始准确说明您的要求:)@WasiAhmad是的,很抱歉给您带来不便。谢谢……)