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

标签 python string formatting replace

太晚了,我一直在尝试编写一个简单的脚本来将点云数据重命名为工作格式。我不知道我做错了什么,因为底部的代码工作正常。为什么 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() 的返回值分配给任何东西。此外,readlinesstr(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/

相关文章:

formatting - 如何格式化数字向量和字符串向量? (Dyalog APL)

java - 如何使 JTextField 或 JFormattedTextField 仅在与 REGEX 模式匹配时才接受输入?

MySQL 5.0 : Output BLOB data in (well-formed) XML format?

python - 按范围扩展 DataFrame

python - 有没有更快的方法来解决以下问题?

python - 将 for 循环的数组结果存储在字典中

c++ - 修改时是否复制 C++ 中的字符串?

c++ - 在 Python 中获取从有符号整数到无符号整数的转换

Java如何从字符串中提取 float 并单独显示

php - 在 PHP 中将 id=1&type=2 之类的字符串转换为数组的最快方法?