简体   繁体   English

替换列表元素中的空格

[英]Replacing whitespaces within list elements

I have a list of tags: 我有一个标签列表:

>>> tags_list
['tag1', 'second tag', 'third longer tag']

How can I replace whitespaces within each element of the list with "+" ? 如何用“ +”替换列表中每个元素内的空格? I was trying to do this with regular expressions but each string remains unchanged: 我试图用正则表达式来做到这一点,但是每个字符串都保持不变:

for tag in tags_list:
    re.sub("\s+" , " ", tag)

What is wrong with my approach ? 我的方法有什么问题?

EDIT: 编辑:

Yes I forgot to mention, that between the words in each tag we can have multiple whitespaces as well as tags can begin or end with whitespaces, since they're parsed from a comma separated string with split(",") : ("First tag, second tag, third tag"). 是的,我忘了提及,每个标签之间的单词之间可以有多个空格,并且标签可以以空格开头或结尾,因为它们是通过使用split(“,”)逗号分隔的字符串来解析的:标签,第二个标签,第三个标签”)。 Sorry for not being precise enough. 抱歉,不够精确。

re.sub() returns a new string, it does not modify its parameter in-place. re.sub()返回一个新字符串,它不会就地修改其参数。

You probably want: 您可能想要:

tags_list = [re.sub(r"\s+", "+", tag) for tag in tags_list]

Also, don't forget the r before the regex or you'll have to double all the backslashes inside (ie the regex you posted won't work). 另外,别忘了正则表达式前的r ,否则您必须将其中的所有反斜杠加倍(即,您发布的正则表达式将不起作用)。

EDIT: I assume replace whitespaces within each element of the list with "+" means collapsing all consecutive whitespace into a single + character. 编辑:我假设replace whitespaces within each element of the list with "+"空格意味着将所有连续的空格折叠成一个+字符。 If not, use r"\\s" instead of r"\\s+" . 如果不是,请使用r"\\s"代替r"\\s+"

What you were doing is not replacing spaces with + , you were replacing multiple whitespace characters with a single space, on top of that you were throwing results out. 您所做的不是用+代替空格,而是用单个空格替换了多个空格字符,此外还抛出了结果。 Here is what you need: 这是您需要的:

>>> tags = ['tag1', 'second tag', 'third longer tag']
>>> [re.sub(r'\s+', '+', i.strip()) for i in tags]
['tag1', 'second+tag', 'third+longer+tag']
>>> tags
['tag1', 'second tag', 'third longer tag']
>>> tags = ['tag1', 'second tag', 'third longer tag']
>>> [ '+'.join(i.split()) for i in tags ]
['tag1', 'second+tag', 'third+longer+tag']

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

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