首页 > 解决方案 > Python中每个字符串前后各加一个空格

问题描述

我想在 Python 中的每个字符串之前和之后添加一个空格。我有 851 个文件。第一个文件包含 219 行。最后一个文件包含 1069 行。有些线只是点,而其他线是数字。我想使用 center() 函数。我试过:

import os, os.path

for x in range(1, 852):
    input_file_name = f"9.{x}.txt"
    output_file_name = os.path.join(f"10.{x}.txt")
    with open(input_file_name) as input_file:
        with open(output_file_name, "w") as output_file:
            for input_line in input_file:
                output_line = input_line.center(2)
                output_file.write(output_line)

这不会增加任何空间。我想要每个字符串前一个空格,每个字符串后一个空格。

输入

.
.
.
.
.
.
.
25
.
.
.
.
55

预期产出

x.x
x.x
x.x
x.x
x.x
x.x
x.x
x25x
x.x
x.x
x.x
x.x
x55x

注意:x代表空间。任何帮助,将不胜感激。谢谢。

标签: python-3.x

解决方案


上述代码中的每个input_line代码末尾都将包含一个换行符,\n因此在您的情况下,您需要删除该\n字符,因此我们可以根据需要使用它rstrip()来删除换行符和格式化行。

代码

 for input_line in f:
        output_line = " " + input_line.rstrip("\n") + " \n"
        output_file.write(output_line)

输出

 . 
 . 
 . 
 . 
 . 
 25 
 . 
 . 
 . 
 . 
 . 
 . 


推荐阅读