我有一个清单。
l = ["This is","'the first 'string","and 'it is 'good"]
我想用“ | space |”替换所有空格 在内的字符串中。
print (l)
# ["This is","'the|space|first|space|'string","and 'it|space|is|space|'good"]
我不能在for循环内使用for循环,而直接使用.replace(),因为字符串不可变
TypeError:'str'对象不支持项目分配
我已经看到以下问题,但没有一个对我有帮助。
在for循环Python中替换字符串元素(3个答案)
在for循环中运行replace()方法?(3个答案)
使用列表理解替换字符串(7个答案)
我已经考虑过使用re.sub,但是无法想到一个合适的正则表达式来完成这项工作。
这对我有用:
>>> def replace_spaces(str) :
... parts = str.split("'")
... for i in range(1,len(parts),2) :
... parts[i] = parts[i].replace(' ', '|')
... return "'".join( parts )
...
>>> [replace_spaces(s) for s in l]
['This is', "'the|first|'string", "and 'it|is|'good"]
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句