我想拆分字串: "3quartos2suítes3banheiros126m2"
以這種格式使用python:
3 quartos
2 suítes
3 banheiros
126m2
有我可以使用的內置函式嗎?我怎樣才能做到這一點?
uj5u.com熱心網友回復:
您可以使用正則運算式來做到這一點,特別是re.findall()
s = "3quartos2suítes3banheiros126m2"
matches = re.findall(r"[\d,] [^\d] ", s)
給出一個串列,其中包含:
['3quartos', '2suítes', '3banheiros', '126m2']
正則運算式解釋(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 m2']
這在126和之間增加了一個空格m2,但這無濟于事。
解釋:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337493.html
下一篇:無效的日期決議器
