Guilherme Celli Fadel
Guilherme Celli Fadel

Reputation: 27

How to split a string in different words

I want to split the string: "3quartos2suítes3banheiros126m²"

in this format using python:

3 quartos


2 suítes

3 banheiros    

126m²

Is there a built-in function i can use? How can I do this?

Upvotes: 1

Views: 59

Answers (1)

pho
pho

Reputation: 25489

You can do this using regular expressions, specifically re.findall()

s = "3quartos2suítes3banheiros126m²"
matches = re.findall(r"[\d,]+[^\d]+", s)

gives a list containing:

['3quartos', '2suítes', '3banheiros', '126m²']

Regex explanation (Regex101):

[\d,]+        : Match a digit, or a comma one or more times
      [^\d]+  : Match a non-digit one or more times

Then, add a space after the digits using re.sub():

result = []
for m in matches:
    result.append(re.sub(r"([\d,]+)", r"\1 ", m))

which makes result =

['3 quartos', '2 suítes', '3 banheiros', '126 m²']

This adds a space between 126 and , but that can't be helped.

Explanation:

Pattern        :
 r"([\d,]+)"   : Match a digit or a comma one or more times, capture this match as a group

Replace with: 
r"\1 "      : The first captured group, followed by a space

Upvotes: 1

Related Questions