Python parse int from string

前端 未结 2 1297
误落风尘
误落风尘 2021-01-07 03:33
test1 = \'name1\'
test2 = \'name2\'
..
test3 = \'name45\'
test4 = \'name1231231\'

Let\'s say I have bunch of strings which start with \'name\' and

相关标签:
2条回答
  • 2021-01-07 04:02

    In Python 3, you could do the following:

    import string
    
    for test in ['name1', 'name2', 'name45', 'name1231231', '123test']:
        print(int(test.strip(string.ascii_letters)))
    

    Giving you:

    1
    2
    45
    1231231
    123
    

    string.ascii_letters gives you a string containing all upper and lowercase letters. Python's strip() function takes a string specifying the set of characters to be removed, which is this case is all alpha characters, thus leaving just the numbers behind.

    Note: This would not be suitable for a string such as 123name456.

    0 讨论(0)
  • 2021-01-07 04:06

    If you know that the prefix is name, then you can either remove just that string, or you can skip the first four letters, like so:

    s = 'name123'
    print int(s.replace('name',''))
    
    s = 'name123'
    print int(s[4:])
    
    0 讨论(0)
提交回复
热议问题