0

I'm having this string in my app which stores different percentage, I want to just extract the percentage value and convert it to int( ). My String looks something like this..

note: there will be one or more blank space(s) before the number.

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)

Thank you in advance.

Manoj Jahgirdar
  • 172
  • 2
  • 12

2 Answers2

4

You need a positive lookahead regex:

import re

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

# Percentage is:  18
Austin
  • 25,759
  • 4
  • 25
  • 48
0

Using regular expression:

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]
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161