在python中用冒号替换空格

时间:2019-05-30 18:48:27

标签: python regex

我有一个键-值对格式的字符串,并用空格分隔。我想用逗号代替空格。

我尝试了replace函数,但是它也用逗号替换了我的值空间。

val = 'name=Ajay age=21 company=abc PVT LTD empid=12345'

我想要的输出:

'name=Ajay,age=21,company=abc PVT LTD,empid=12345'

2 个答案:

答案 0 :(得分:3)

您可以匹配<word>=模式,然后替换它们:

import re    
val = 'name=Ajay age=21 company=abc PVT LTD empid=12345'

pattern = re.compile(r' \w+=')
pattern.sub(lambda match: match.group().replace(' ', ','), val)

# Output
# 'name=Ajay,age=21,company=abc PVT LTD,empid=12345'

This也应该是sublambda一起工作的良好参考

答案 1 :(得分:0)

怎么样:

\w+=[^=]+(?: |$)

在Regex101上检查它:https://regex101.com/r/GgbqxB/1