0

Let's say that I have a string like this: 'Hello \n this world is nice'. When calling the print function print('Hello \n this world is nice') the result would be such that a new line is introduced after 'Hello'.

If I wanted to print exactly

'Hello \n this world is nice'

so such that \n appears in the output of the print function as two characters), how could I do it?

CristiFati
  • 38,250
  • 9
  • 50
  • 87
Ile
  • 163
  • 1
  • 7

3 Answers3

1

One way could be using [Python.Docs]: Built-in Functions - repr(object):

txt = "Hello \n this world is nice"
>>> print(txt)
Hello
 this world is nice
>>> print(repr(txt))
'Hello \n this world is nice'
CristiFati
  • 38,250
  • 9
  • 50
  • 87
1

Escape the \ to print is as literal:

print('Hello \\n this world is nice')

Or add an r do interpret all in the string as literal (raw):

print(r'Hello \n this world is nice')
b3nj4m1n
  • 502
  • 7
  • 24
0

Look here

How to print a string literally in Python

z = 'hello\n hello' 
print(repr(z))
>>> hello\n hello
marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37