Search code examples
pythonpython-3.xstringfull-text-search

Adding Text at a specific postion in Python


I have a multiline text, something like this -

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

And I have a text value -

b = '00000000'       # to insert in between

I need to insert the string b into string a at specific position, say (2,1) (i.e. line 2, char 1), since this is how I am getting the result of pattern match from some module (in form of line_number, char_number in line).

Expected Output -

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

Many thanks!


Solution

  • You can use str.splitlines, change the required line and join the lines back:

    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))
    

    Prints:

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