Find the index of the first digit in a string

前端 未结 14 735
清酒与你
清酒与你 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}
    
    0 讨论(0)
  • 2020-12-28 12:59

    Thought I'd toss my method on the pile. I'll do just about anything to avoid regex.

    sequence = 'xdtwkeltjwlkejt7wthwk89lk'
    i = [x.isdigit() for x in sequence].index(True)
    

    To explain what's going on here:

    • [x.isdigit() for x in sequence] is going to translate the string into an array of booleans representing whether each character is a digit or not
    • [...].index(True) returns the first index value that True is found in.
    0 讨论(0)
提交回复
热议问题