在Python中的每个字符串前后添加一个空格

时间:2020-04-07 06:00:14

标签: python-3.x

我想在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

NB:x代表空格。任何帮助,将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:2)

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

代码

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

输出

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

答案 1 :(得分:0)

黄Yellow钱币

据我所知,您可以使用.join字符串方法将任何值添加到字符串的开头和结尾。

#insert character into string with string-method .join

string_1 = 'this is a string without a space at the beginning or end. Put a X where the spacing should be'


iterable_join = ['X', 'X',] 
string_1 = string_1.join(iterable_join)
print(string_1)

控制台中的输出是:

X这是一个字符串,开头或结尾没有空格。放一个x 间距应为X

我不知道这是否会产生过多的开销,但确实可以。 有关更多信息,请参见:

https://www.tutorialspoint.com/python/string_join.htm

如果它可以帮助您解决问题,请标记为答案。 最好, CJ

相关问题