0

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!

bbesase
  • 731
  • 4
  • 16
  • 31

3 Answers3

3

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']
Sukrit Kalra
  • 30,727
  • 7
  • 64
  • 70
2
finalPathList = map(lambda x: x.replace('\\', '/'), pathList)

map is a nice way to apply a function to each list item.

Ofiris
  • 5,907
  • 5
  • 34
  • 57
1

Correcting your code...

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