【问题标题】:Replacing characters within a list替换列表中的字符
【发布时间】:2013-05-20 18:05:06
【问题描述】:

我必须替换列表中每个元组中的某些字符。我知道如何只用一个基本字符串来完成。

import string
s = 'This:is:awesome'
ss = s.replace(':', '/')
print ss

但是,我将如何遍历列表?

import string
finalPathList = []
pathList = ['List of 10+ file path names']
for lines in pathList:
    ss = pathList.replace('\', '/')
    print ss
    finalPathList.append(ss)

我需要做的就是检查每个文件名元组,并将所有 "\" 替换为 "/" 。

任何帮助将不胜感激!

【问题讨论】:

  • 将replace 应用于lines,而不是pathList。
  • 他真的需要import string吗?
  • 另一方面,您不能使用"\",使用"\\" 或更好地使用原始字符串。 stackoverflow.com/questions/11168076/…

标签: python replace


【解决方案1】:

这样的?

>>> pathList = [r"C:\Users", r"C:\Documents", r"C:\Downloads\Test"]
>>> finalPathList = []
>>> for element in pathList:
          finalPathList.append(element.replace("\\", "/"))


>>> finalPathList
['C:/Users', 'C:/Documents', 'C:/Downloads/Test']

或者通过使用列表理解。

>>> finalPathList = [elem.replace("\\", "/") for elem in pathList]
>>> finalPathList
['C:/Users', 'C:/Documents', 'C:/Downloads/Test']

【讨论】:

  • +1 使用原始字符串,否则 "C:\test" 之类的内容会导致不需要的结果。
【解决方案2】:
finalPathList = map(lambda x: x.replace('\\', '/'), pathList)

map 是将函数应用于每个 list 项的好方法。

【讨论】:

  • 感谢您的评论!删除了我的错误。
【解决方案3】:

正在更正您的代码...

finalPathList = []
pathList = ['List of 10+ file path names']
for lines in pathList:
    ss = lines.replace('\\', '/')
    print ss
    finalPathList.append(ss)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 2013-11-15
    • 2019-01-30
    • 2021-05-22
    • 2019-02-26
    • 2010-10-20
    • 2014-01-24
    相关资源
    最近更新 更多