Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string on non digits

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.

like image 256
myol Avatar asked Feb 17 '19 13:02

myol


2 Answers

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.

like image 162
Patrick Artner Avatar answered Oct 02 '22 12:10

Patrick Artner


Try this:

orig = '0 1,2.3-4:5;6d7'
[i for i in orig if i.isdigit()]
like image 26
Mehrdad Pedramfar Avatar answered Oct 02 '22 12:10

Mehrdad Pedramfar