繁体   English   中英

如何在不同的单词中拆分字符串

[英]How to split a string in different words

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

以这种格式使用python:

3 quartos


2 suítes

3 banheiros    

126m²

有我可以使用的内置函数吗? 我怎样才能做到这一点?

您可以使用正则表达式来做到这一点,特别是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM