I am trying to split a string on any char that is not a digit.
orig = '0 1,2.3-4:5;6d7'
results = orig.split(r'\D+')
I expect to get a list of integers in results
0, 1, 2, 3, 4, 5, 6, 7
but instead I am getting a list with a single string element which matches the original string.
Well ... you are using str.split()
- which takes characters to split at - not regex. Your code would split on any '\D+'
- string inside your text:
orig = 'Some\\D+text\\D+tosplit'
results = orig.split(r'\D+') # ['Some', 'text', 'tosplit']
You can use re.split() instead:
import re
orig = '0 1,2.3-4:5;6d7'
results = re.split(r'\D+',orig)
print(results)
to get
['0', '1', '2', '3', '4', '5', '6', '7']
Use data = list(map(int,results))
to convert to int.
Try this:
orig = '0 1,2.3-4:5;6d7'
[i for i in orig if i.isdigit()]
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