Reputation: 1382
I have a string
Best product25.075.0Product29.029.0
And now I need to split this string to
'Best product' '25.0' '75.0' , 'Product' '29.0' '29.0'
How can i achieve this?
Upvotes: 3
Views: 125
Reputation: 12005
You can use re.findall
to find all words (containing letter or space - matching pattern [a-zA-Z ]+
) or all numbers (one or more digits followd by a dot and zero - matching pattern \d+.0
)
string = 'Best product25.075.0Product29.029.0'
import re
re.findall(r'[a-zA-Z ]+|\d+(?:.0)?', string)
# ['Best product', '25.0', '75.0', 'Product', '29.0', '29.0']
Upvotes: 5
Reputation: 786
A very similar way to do it is:
import re
string = 'Best product25.075.0Product29.029.0'
re.findall(r'[^\d]+|\d+.0', string)
The code only distinguishes between non-digits [^\d]+
and digits plus dot zero \d+.0'
. So it matches also additional characters like _
.
Upvotes: 2