Search code examples
pythonclassextractuser-input

How can I extract a specific part of an input?


First of all I am making some sort of timer (you'll know why I say this). I have a class and each parameter takes an integer as input. Now, whenever I ask the user to input a value (for example, they could input "3hrs 2mins 1s") I want to get the numbers; but that's not the matter. The matter is that idk how I could get rid of those words, like getting rid of "hrs" so I can just take the number (eventually I would have to convert it into a int). Any ideas? Hope I was clear.


Solution

  • You can use a regular expression to match the numbers only. Using re.findall() you can get a list of results that match the given regular expression.

    import re
    
    user_input = '11hrs 2mins 1s'           # You can use `input()`
    time = re.findall('\d+', user_input)    # Find all results
    time = [int(i) for i in time]           # Convert each of the numbers to digits
    
    print(time)
    

    Here, \d means any digit and + means occurring more than once. Thus using findall() function you get a list of numbers captured within the string.

    Output


    [11, 2, 1]