【问题标题】:Adding Text at a specific postion in Python [closed]在 Python 中的特定位置添加文本 [关闭]
【发布时间】:2021-05-31 18:16:20
【问题描述】:

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

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.
"""

非常感谢!

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后然后就您的算法或技术提出一个具体的问题。 Stack Overflow 并不打算取代现有的文档和教程。这是您重复有关字符串处理的教程的地方;这不是堆栈溢出问题。

标签: python python-3.x string full-text-search


【解决方案1】:

您可以使用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.

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2020-03-06
    • 1970-01-01
    • 2017-02-06
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多