如何用其他东西替换列表中某些内容的所有重复

时间:2013-07-29 17:35:26

标签: python python-3.x

很抱歉,如果标题有点模糊,但我想查看一个列表,并将所有'\\'替换为'/'。这是一个例子:

list = ['C:/dir\\file.txt', 'C:/dir\\example.zip', 'C:/dir\\example2.zip']

出于可读性原因,我想使用'\\'过滤掉所有单个路径中的'/'

2 个答案:

答案 0 :(得分:1)

使用str.replace

>>> 'C:/dir\\file.txt'.replace('\\', '/')
'C:/dir/file.txt'

str.replace应用于所有路径,您将获得替换路径。

>>> paths = list = ['C:/dir\\file.txt', 'C:/dir\\example.zip', 'C:/dir\\example2.zip']
>>> paths = [path.replace('\\', '/') for path in paths]
>>> paths
['C:/dir/file.txt', 'C:/dir/example.zip', 'C:/dir/example2.zip']

答案 1 :(得分:0)

你应该使用os.path而不是手工处理路径,但是既然你必须这样做,你就去:

[re.sub("\\\\",'/',x) for x in list]