How to split a string but keep decimal values intact (Python)


#1

If I have a string that contains decimal values, how can I split it to keep the decimals intact?

For example:

Rhino123.45Python987.654

I want the results to look like this:

[R,h,i,n,o,123.45,P,y,t,h,o,n,987.654]

This is the closest I could get:

import re
string = "Rhino123.45Python987.654"
strChar = re.findall(r’\d+|\D’,string)
print strChar

…but the numbers are fractured at the decimal point:

[‘R’, ‘h’, ‘i’, ‘n’, ‘o’, ‘123’, ‘.’, ‘45’, ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘987’, ‘.’, ‘654’]

Thanks,

Dan


#2

I found a solution shortly after posting this:

import re
string = "Rhino123.45Python987.654"
strChar = re.findall(r’[0-9.]+|\D’,string)
print strChar

I’ll leave this posted in case anyone else ever needs to search for this solution.

Dan


(Menno Deij - van Rijswijk) #3

Yeah, regexes are your best friend, but sometimes also worst enemy :smile:


#4

Yeah, how true! It doesn’t seem like regular expressions have changed much from VBScript to Python. I recall it being a pain way back when I wrote all these scripts 10 years ago.

By the way, I’ve found an even better solution for this particular issue since I last posted:

listChar = re.findall(r’[0-9.]+|[^0-9.]’, string)