如何在读取文本文件时去除空格

huangapple go评论78阅读模式
英文:

How to take out spaces when reading a text file

问题

with open("zeaaa.txt", "rb") as file:
    byte = file.read(6)
    byte = byte.replace(b" ", b"")  # Replace spaces with nothing
    print(byte.decode())

    while byte:
        byte = file.read(6)
        byte = byte.replace(b" ", b"")  # Replace spaces with nothing
        print(byte.decode())
英文:

I am trying to write code that will transform a 160x160 table (where each column is a value of 5 digits and a dot, ex: "1.02456") into a single column. For example, the code would transform:

1 2 3 4 5  ->
1
2
3
4
5

However, the code I have currently prints the columns with the spaces included. Here is the current code:

with open("zeaaa.txt", "rb") as file:
    byte = file.read(6)  
    byte.replace(" ", "")
    print(byte.decode)
 
    while byte:
        byte = file.read(6)  
        byte.replace(" ", "")
        print(byte.decode())

How can I modify this code to remove the spaces and print the single column as described above?

Here is an example of the problem.

答案1

得分: 1

查看Python文档replace 返回 一个修改后的副本,不执行原地修改。由于您没有分配此结果,它将丢失。

英文:

See Python documentation: replace returns a modified copy, it performs no in-place modification. Since you don't assign this result, it is lost.

huangapple
  • 本文由 发表于 2023年6月16日 15:56:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76488092.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定