Converting regex whitespace characters from list into string

时间:2016-12-09 13:01:19

标签: python regex

So i want to convert regex whitespaces into a string for example

list1 = ["Hello","\s","my","\s","name","\s","is"]

And I want to convert it to a string like

"Hello my name is" 

Can anyone please help. But also if there was characters such as "\t" how would i do this?

3 个答案:

答案 0 :(得分:5)

list = ["Hello","\s","my","\s","name","\s","is"]
str1 = ''.join(list).replace("\s"," ")

Output :

>>> str1
'Hello my name is'

Update :

If you have something like this list1 = ["Hello","\s","my","\s","name","\t","is"] then you can use multiple replace

>>> str1 = ''.join(list).replace("\s"," ").replace("\t"," ")
>>> str1
'Hello my name is'

or if it's only \t

str1 = ''.join(list).replace("\t","anystring")

答案 1 :(得分:2)

我强烈建议使用前面一个答案中提到的连接字符串函数,因为它不那么详细。但是,如果您完全需要使用正则表达式来完成任务,那么这就是答案:

import re

list1 = ["Hello","\s","my","\s","name","\s","is"]
list_str = ''.join(list1)

updated_str = re.split('\\\s', list_str)
updated_str = ' '.join(updated_str)

print(updated_str)

输出是:

'Hello my name is'

要使用原始字符串表示法,请将第5行代码替换为下面的代码:

updated_str = re.split(r'\\s', list_str)

两者都有相同的输出结果。

答案 2 :(得分:0)

You don't even need regular expressions for that:

s = ' '.join([item for item in list if item is not '\s'])

Please note that list is an invalid name for a variable in python as it conflicts with the list function.