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.

2

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

Comments

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] 

5 Comments

This doesn't work for inp_str = "demo 11 percentage is 18%".
Yes, I know that my solution will not handle the above scenario but the question was not asked only to extract numbers that precede the % sign. Anyway, I have updated the answer.
result ='bFilesystem Size Used Avail Use% Mounted on\n/dev/sda4 30G 20G 8.4G 71% /\n' this is my string to be precise
@ManojJahgirdar please mention your requirements precisely from next time :)
@WasiAhmad yes sorry for the inconvenience. thank you.. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.