I have a string like "GoTo: 7018 6453 12654\n"
I just want get the number something like this ['7018', '6453', '12654']
, I tries regular expression but I can't split string to get just number here is my code:
Sample 1:
splitter = re.compile(r'\D');
match1 = splitter.split("GoTo: 7018 6453 12654\n")
my output is: ['', '', '', '', '', '', '', '', '7018', '6453', '12654', '']
Sample 2:
splitter = re.compile(r'\W');
match1 = splitter.split("GoTo: 7018 6453 12654\n")
my output is: ['GoTo', '', '7018', '6453', '12654', '']
This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.
Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
>>> re.findall(r'\d+', 'GoTo: 7018 6453 12654\n')
['7018', '6453', '12654']
If all your numbers are positive integers, you can do that without regular expressions by using the isdigit() method:
>>> text = "GoTo: 7018 6453 12654\n"
>>> [token for token in text.split() if token.isdigit()]
['7018', '6453', '12654']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With