Find the index of the first digit in a string

前端 未结 14 849
清酒与你
清酒与你 2020-12-28 12:29

I have a string like

\"xdtwkeltjwlkejt7wthwk89lk\"

how can I get the index of the first digit in the string?

14条回答
  •  暖寄归人
    2020-12-28 12:55

    Here is a better and more flexible way, regex is overkill here.

    s = 'xdtwkeltjwlkejt7wthwk89lk'
    
    for i, c in enumerate(s):
        if c.isdigit():
            print(i)
            break
    

    output:

    15
    

    To get all digits and their positions, a simple expression will do

    >>> [(i, c) for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()]
    [(15, '7'), (21, '8'), (22, '9')]
    

    Or you can create a dict of digit and its last position

    >>> {c: i for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()}
    {'9': 22, '8': 21, '7': 15}
    

提交回复
热议问题