Search code examples
pythonstringintmeasurement

Convert measurement from String to Int or Float


I have the string

var = '7 msecs'
#var = int(var)
#var = float(var)

And I want to convert that to an integer (7), or float (7.0). This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.

How can I do this in Python?

I want a good way to do this, without having to do

var = int(var.split(' ')[0])

It should also work for:

'10mm' or '10.55€' 

Considered duplicate (Python: Extract numbers from a string)

This question is different, as I'm trying to replicate the ability of parseInt/parseFloat in javascript which only returns the numbers at the beginning of a string. This other question is looking for all numbers in a string.

#What I want:
'123mm' -> 123
'123mm1' -> 123

Solution

  • If you have white space, use split:

    >>> s = "123 msecs2"
    >>> int(s.split()[0])
    123
    

    If you want to take the numbers from the start of a string only without white space (or using regex), try this:

    >>> s = "123msecs2"
    >>> int("".join(list(next(iter(())) if not x.isdigit() else x for x in s)))
    123
    

    Note, it takes inspiration from the discussion here about breaking out of list comprehensions.