Splitting a string where it switches between numeric and alphabetic characters

前端 未结 4 1192
闹比i
闹比i 2020-12-30 02:20

I am parsing some data where the standard format is something like 10 pizzas. Sometimes, data is input correctly and we might end up with 5pizzas i

4条回答
  •  太阳男子
    2020-12-30 02:48

    You ask for a way to split a string on digits, but then in your example, what you actually want is just the first numbers, this done easily with itertools.takewhile():

    >>> int("".join(itertools.takewhile(str.isdigit, "10pizzas")))
    10
    

    This makes a lot of sense - what we are doing is taking the character from the string while they are digits. This has the advantage of stopping processing as soon as we get to the first non-digit character.

    If you need the later data too, then what you are looking for is itertools.groupby() mixed in with a simple list comprehension:

    >>> ["".join(x) for _, x in itertools.groupby("dfsd98sd8f68as7df56", key=str.isdigit)]
    ['dfsd', '98', 'sd', '8', 'f', '68', 'as', '7', 'df', '56']
    

    If you then want to make one giant number:

    >>> int("".join("".join(x) for is_number, x in itertools.groupby("dfsd98sd8f68as7df56", key=str.isdigit) if is_number is True))
    98868756
    

提交回复
热议问题