3

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?

2
  • "25.075.0" is inherently ambiguous, though. Is it "25.0", "75.0" or "25.07", "5.0"? You need to assume that each number has exactly one place after the decimal point for any of the answers to work. It would be better if you could modify whatever produces that string to use a separating character. Commented Jun 28, 2018 at 10:10
  • this string is just output, so i presented as it is. and it's "25.0", "75.0" Commented Jun 28, 2018 at 10:37

2 Answers 2

5

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']
Sign up to request clarification or add additional context in comments.

3 Comments

note that this will only work if the "words" dont contain any numbers
Than it will be a problem
@HeinerFrüh Updated the answer to work with words containing numbers without decimal points
2

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 _.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.