Home > Net >  Get lines of multi-line string, Python
Get lines of multi-line string, Python

Time:10-24

I'm trying to convert large string in lines, but failing if \n is occurred in it.

Example string

s1 = """
x = 10
y = 20
print(f"Sample Calculator:\n{x}   {y} = {x y}")"""
lines = s1.splitlines() # Similar results on lines = s1.split('\n')
print(*lines, sep='\n------\n')

output:


------
x = 10
------
y = 20
------
print(f"Sample Calculator:
------
{x}   {y} = {x y}")

Required output:


------
x = 10
------
y = 20
------
print(f"Sample Calculator:\n{x}   {y} = {x y}")

CodePudding user response:

Change this line to:

print(f"Sample Calculator:\\n{x} {y} = {x y}")"""

(I've escaped the backslash that will make it visible in the print instruction instead of treating it as a new line indicator)

output

CodePudding user response:

To preserve backslashes literally, you use a raw-string, denoted by the prefix r, so that you don't have to escape every occurrence of a backslash with another backslash:

s1 = r"""
x = 10
y = 20
print(f"Sample Calculator:\n{x}   {y} = {x y}")"""
  • Related