在 Python 中的特定位置添加文本

Adding Text at a specific postion in Python

我有一个多行文本,像这样 -

a = """
Hi this is a sample line
Another line
Final line of the example.
"""

我有一个文本值 -

b = '00000000'       # to insert in between

我需要在特定位置将字符串 b 插入字符串 a,比如 (2,1)(即第 2 行,第 1 个字符),因为我就是这样从某个模块获取模式匹配的结果(以 line_number、char_number 的形式)。

预期输出 -

a = """
Hi this is a sample line
A00000000nother line                          # <-- Entered string in line 2, after char 1 i.e. (2,1)
Final line of the example.
"""

非常感谢!

您可以使用 str.splitlines,更改所需的行并加入行:

a = """
Hi this is a sample line
Another line
Final line of the example.
"""

b = "00000000"

pos = 2, 1

lines = a.splitlines()
lines[pos[0]] = lines[pos[0]][: pos[1]] + b + lines[pos[0]][pos[1] :]

print("\n".join(lines))

打印:


Hi this is a sample line
A00000000nother line
Final line of the example.