RnRoger
RnRoger

Reputation: 690

Strip "\n" from a multiline sting, except when inline

If I have a multiline string that contains "\n" as part of the text itself, for example:

python_text = """
@commands.command()
def multi():
    print("Three\nLines\nHere")
"""

How can I remove all newlines except those in the text itself? I've tried creating a list with splitlines() but the multiline string will also be split on the \n's in the text itself. Using splitlines(True) in combination with strip() doesn't work for the same reasons.

print(python_text.splitlines())

Output (formatted):

[
'@commands.command()', 
'def multi():', 
'    print("Three', 
'Lines', 
'Here")'
]

Whilst my desired output is:

[
'@commands.command()', 
'def multi():', 
'    print("Three\nLines\nHere")'
]

(Or a multiline string print instead of list print, but in the same format)

Is there any way I can only strip the 'trailing' newline characters from a multiline string? If anything is unclear please let me know and I'll try to explain further.

Edit: Corrected explanation about splitlines() and strip().

Upvotes: 2

Views: 126

Answers (1)

Primusa
Primusa

Reputation: 13498

You have to escape your newlines. In this case you can just make it a raw string literal:

python_text = r"""
@commands.command()
def multi():
    print("Three\nLines\nHere")
"""

print(python_text.splitlines())
>>>['', '@commands.command()', 'def multi():', '    print("Three\\nLines\\nHere")']

Upvotes: 3

Related Questions