【问题标题】:How to split a string in different words如何将字符串拆分为不同的单词
【发布时间】:2021-10-26 14:58:10
【问题描述】:

我要拆分字符串:"3quartos2suítes3banheiros126m²"

使用python以这种格式:

3 quartos


2 suítes

3 banheiros    

126m²

有没有我可以使用的内置函数?我该怎么做?

【问题讨论】:

标签: python python-3.x string


【解决方案1】:

您可以使用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 之间添加一个空格,但这无济于事。

解释:

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

【讨论】:

  • @GuilhermeCelliFadel 查看我的编辑。括号[ ] 使正则表达式匹配括号中指定的任何字符。所以我只是把\d+改成了[\d,]+
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 2011-04-22
  • 2023-01-22
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多