Cleanest way to obtain the numeric prefix of a string

后端 未结 9 1384
醉话见心
醉话见心 2021-01-07 19:21

What is the cleanest way to obtain the numeric prefix of a string in Python?

By \"clean\" I mean simple, short, readable. I couldn\'t care less about performance, a

9条回答
  •  天涯浪人
    2021-01-07 19:58

    One way, but not very efficient since it works through the whole string without break would be:

    input_string = '123abc456def'
    [input_string[:c] for c in range(len(input_string)) if input_string[:c].isdigit()][-1]
    

    This appends each substring with increasing size if it is a digit and then appends it. So the last element is the one you look for. Because it is the longest startstring that is still a digit.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题