Search code examples
pythonstringnumbers

string related question with numbers included


I would like to split M22 (so split the string M and the number 22)

I tried finding help from the internet, but most solutions are too complicated too begin with.


Solution

  • If it's always : 1 letter 2 digit, just slice the string

    v = "M22"
    letter, digits = v[0], v[1:]
    print(letter, digits) # M 22
    

    If the amount of each is variable, use a regex

    import re
    v = "M22"
    letter, digits = re.search("([A-Z]+)(\d+)", v).groups()
    print(letter, digits) # M 22