python-3.x - 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
代表空间。任何帮助,将不胜感激。谢谢。
解决方案
上述代码中的每个input_line
代码末尾都将包含一个换行符,\n
因此在您的情况下,您需要删除该\n
字符,因此我们可以根据需要使用它rstrip()
来删除换行符和格式化行。
代码
for input_line in f:
output_line = " " + input_line.rstrip("\n") + " \n"
output_file.write(output_line)
输出
.
.
.
.
.
25
.
.
.
.
.
.
推荐阅读
- r - 给定一个拟合模型,如何预测下个月?
- kubernetes - Helm Chart 的 Chart.yaml 中属性关键字的作用是什么?
- ssh - 使用 sed over ssh 将项目添加到列表
- firefox - 在控制台中禁用 Firefox 事件日志
- javascript - 如何用另一个对象的值减去一个对象的值?
- nginx - 使用 $request_uri NGINX 匹配基本 URL
- python - 变换图。您必须使用 dtype float 和 shape 为占位符张量“image”提供一个值
- angular - 带角度 API 调用的 Typeahead
- html - 测量 HTML 文本传输时间的工具?
- django - AttributeError:“函数”对象在函数视图中没有属性“get_extra_actions”