Search code examples
pythonstringjoinnumberssubstring

How do I get a number from a string in python?


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.


Solution

  • 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)