太晚了,我一直在尝试编写一个简单的脚本来将点云数据重命名为工作格式。我不知道我做错了什么,因为底部的代码工作正常。为什么 for 循环中的代码不起作用?它正在将它添加到列表中,但它只是没有被替换功能格式化。抱歉,我知道这不是调试器,但我真的坚持这个,其他人可能需要 2 秒才能看到问题。
# Opening and Loading the text file then sticking its lines into a list []
filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
lines = text.readlines()
linesNew = []
temp = None
# This bloody for loop is the problem
for i in lines:
temp = str(i)
temp.replace(' ', ', ',2)
linesNew.append(temp)
# DEBUGGING THE CODE
print(linesNew[0])
print(linesNew[1])
# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)
text.close()
最佳答案
您没有将 replace()
的返回值分配给任何东西。此外,readlines
和 str(i)
是不必要的。
试试这个:
filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []
for line in text:
# i is already a string, no need to str it
# temp = str(i)
# also, just append the result of the replace to linesNew:
linesNew.append(line.replace(' ', ', ', 2))
# DEBUGGING THE CODE
print(linesNew[0])
print(linesNew[1])
# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)
text.close()
关于python - 在 for 循环中运行 replace() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7814997/