简体   繁体   中英

Best non-regex way to remove all characters after and including the first non-digit in Python

Assume a string of 5 chars. The title, I think, is clear, but here are some examples:

'716-0' --> '716'
'77820' --> '77820'

Regex works fine

import re
re.findall(r'\d+', '716-0')[0]

but how about a good non-regex way?

Regex is probably the best way to do it, but if for whatever reason you want to avoid it, you can make use of str.isdigit() and itertools.takewhile() :

from itertools import takewhile

string = "716-0"
number = "".join(takewhile(str.isdigit, string))
def trim(x):
    output=[]
    for digit in x:
        if digit in [str(x) for x in range(10)]:
            output.append(digit)
        else:
            break
    return ''.join(output)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM