在for循环中运行replace()方法?

Sac*_*try 5 python string formatting replace

它已经很晚了,我一直在努力研究一个简单的脚本,将点云数据重命名为工作格式.我不知道我做错了什么,因为底部的代码工作得很好.为什么for循环中的代码不起作用?它将它添加到列表中,但它没有被replace函数格式化.对不起,我知道这不是一个调试器,但我真的被困在这上面,其他人可能需要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()
Run Code Online (Sandbox Code Playgroud)

cho*_*own 4

您没有将 的返回值分配replace()给任何东西。另外,readlinesstr(i)都是不必要的。

\n\n

尝试这个:

\n\n
filename = "/Users/sacredgeometry/Desktop/data.txt"\ntext = open(filename, \'r\')\nlinesNew = []\n\nfor line in text:\n    # i is already a string, no need to str it\n\xc2\xa0 \xc2\xa0 # temp = str(i)\n\n    # also, just append the result of the replace to linesNew:\n\xc2\xa0 \xc2\xa0 linesNew.append(line.replace(\' \', \', \', 2))\n\n# DEBUGGING THE CODE \xc2\xa0 \xc2\xa0\nprint(linesNew[0])\nprint(linesNew[1])\n\n# Another test to check that the replace works ... It does!\ntest2 = linesNew[0].replace(\' \', \', \',2)\ntest2 = test2.replace(\'\\t\', \', \')\nprint(\'Proof of Concept: \' + \'\\n\' + test2)  \n\ntext.close()\n
Run Code Online (Sandbox Code Playgroud)\n