我想了解python3.X中使用的以下技术的以下结果来执行某些操作。请考虑以下使用不同技术的代码尝试获得相同的结果。
def addSlash(fname):
if isinstance(fname, str):
if " " in fname:
return fname.replace(" ", "\ ")
# example output
a = "ab c"
a = addSlash(a)
print(a)
print()
# list of interest
files = ["spaces file1", "spaces file2", "spaces file3"]
for f in files:
f = addSlash(f)
# this prints correct result but list elements are not permanently having the change.
print(f)
print('\nThis did not change..')
print(files)
print('\nTrying the old way gives 2 slashes as well..')
files = ["spaces file1", "spaces file2", "spaces file3"]
for i in range(0, len(files)):
files[i] = addSlash(files[i])
print(files)
print('\nTrying this way give as different results, putting 2 slashes instead of one for some reason')
files = ["spaces file1", "spaces file2", "spaces file3"]
files = [addSlash(f) for f in files]
print(files)
print('\nSame with this one, same results as above.')
files = ["spaces file1", "spaces file2", "spaces file3"]
f = list(map(lambda x: x.replace(" ", "\ "), files))
print(f)
运行时上述输出如下:
ab\ c
spaces\ file1
spaces\ file2
spaces\ file3
This did not change..
['spaces file1', 'spaces file2', 'spaces file3']
Trying the old way gives 2 slashes instead of one!
['spaces\\ file1', 'spaces\\ file2', 'spaces\\ file3']
Trying this way give as different results, putting 2 slashes as well!
['spaces\\ file1', 'spaces\\ file2', 'spaces\\ file3']
Same with this one, same results as above.
['spaces\\ file1', 'spaces\\ file2', 'spaces\\ file3']
有人可以对每种技术发表评论并解释它为什么不起作用吗?