[英]Replacing characters within a list
I have to replace certain characters in each tuple in a list.I know how to do it with just a basic string. 我必须替换列表中每个元组中的某些字符。我知道如何仅使用基本字符串来完成此操作。
import string
s = 'This:is:awesome'
ss = s.replace(':', '/')
print ss
However, how would I go about looping through a list? 但是,我将如何遍历列表?
import string
finalPathList = []
pathList = ['List of 10+ file path names']
for lines in pathList:
ss = pathList.replace('\', '/')
print ss
finalPathList.append(ss)
All I need to do is go through each tuple of filenames, and replace all of the "\\"
's with "/"
's. 我需要做的是遍历文件名的每个元组,并将所有
"\\"
替换为"/"
。
Any help would be greatly appreciated! 任何帮助将不胜感激!
Something like this? 像这样吗
>>> 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']
Or by using List Comprehension. 或通过使用列表理解。
>>> finalPathList = [elem.replace("\\", "/") for elem in pathList]
>>> finalPathList
['C:/Users', 'C:/Documents', 'C:/Downloads/Test']
finalPathList = map(lambda x: x.replace('\\', '/'), pathList)
map
是一种将功能应用于每个list
项的好方法。
Correcting your code... 正在更正您的代码...
finalPathList = []
pathList = ['List of 10+ file path names']
for lines in pathList:
ss = lines.replace('\\', '/')
print ss
finalPathList.append(ss)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.