Home > Net >  How do I get a number from a string in python?
How do I get a number from a string in python?

Time:12-08

Need help guys,

s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."

How to extract the number which has minutes next to it. Then divide the number with 2 and get this below string as output,

“I waited only 30 minutes. I cannot wait any longer. My home is 20 miles away.”

“60 minutes” should be replaced “only 30 minutes”. Instead of 60, there could be any number.

CodePudding user response:

regular expression replacement functions are the best suited for that task

One line

import re
s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."

print(re.sub("(\d )( minutes)",lambda m:str(int(m.group(1))//2) m.group(2),s))

prints:

I waited 30 minutes. I cannot wait any longer. My home is 20 miles away.

the lambda function is fed with regex groups in input, it "just" converts the first argument to integer, divides it by 2, then converts back to string, and rebuilds the time string.

CodePudding user response:

If you can, declare it as f“I waited {myTime (60)} minutes. I cannot wait any longer. My home is 20 miles away.”. Then you can simply change the variable integer myTime.

If you really have to take it from raw input, I'd recommend splitting the string first. Then you can loop over each word and check if int(word) is a number.

CodePudding user response:

Another method using for loop,

def isnum(s):
    res= False
    try:
        n = int(s)
        res = True
    except:
        pass
    return res

s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."

j = -1

s_list = s.split(' ')
res = ""
for i in s_list:
    j  = 1
    if isnum(i):
        if s_list[j 1] in ['minute', 'minute.', 'minutes', 'minutes.']:
            i = str(int((int(i)/2)))
    res  = i   " "

print(res)
  • Related