Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python parse int from string

Tags:

python

test1 = 'name1'
test2 = 'name2'
..
test3 = 'name45'
test4 = 'name1231231'

Let's say I have bunch of strings which start with 'name' and are followed by a number of any length.

How can I parse out the number in the string?

Is regex the only way or is there a built-in module that can accomplish this task?

like image 725
ealeon Avatar asked Nov 27 '22 08:11

ealeon


1 Answers

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 in this case is all alpha characters, thus leaving just the numbers behind.

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


If there are just known common prefixes/suffixes to all strings, the following approach could also be used in Python 3.9:

for test in ['name1', 'name2', 'name45', 'name1231231', '123test']:
    print(test.removeprefix('name').removesuffix('test'))
like image 119
Martin Evans Avatar answered Dec 05 '22 16:12

Martin Evans