您可以使用regular expressions 来执行此操作,特别是re.findall()
s = "3quartos2suítes3banheiros126m²"
matches = re.findall(r"[\d,]+[^\d]+", s)
给出一个列表,其中包含:
['3quartos', '2suítes', '3banheiros', '126m²']
正则表达式解释(Regex101):
[\d,]+ : Match a digit, or a comma one or more times
[^\d]+ : Match a non-digit one or more times
然后,使用re.sub()在数字后添加一个空格:
result = []
for m in matches:
result.append(re.sub(r"([\d,]+)", r"\1 ", m))
这使得result =
['3 quartos', '2 suítes', '3 banheiros', '126 m²']
这会在126 和m² 之间添加一个空格,但这无济于事。
解释:
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