Home > Blockchain >  How can I Print \n after each sentence?
How can I Print \n after each sentence?

Time:05-06

I'm a newbie and was trying something..

Example:

text = """
Hello, how are you?
I'm fine and you?
Same as always..
"""
print(text)

And want this output:

Hello, how are you? \nI'm fine and you? \nSame as always..

Sorry if this question is silly.. I'm newbie and was searching this for 4 days but didn't found anything related to this and finally decided to ask it on stack overflow

CodePudding user response:

You can use repr() for this purpose:

print(repr(text))

This will also add quotes, and escape other characters like tabs, backspaces, etc.

Other option is to replace the newlines:

print(text.replace('\n', '\\n'))

This will escape only line breaks and no other special characters.

CodePudding user response:

Notice that there is a "\n" at the start of the string that you want to print. You left it out in your question.

text = """
Hello, how are you?
I'm fine and you?
Same as always..
"""

for letter in text:
    if letter == "\n":
        print("\\n",end="")
    else:
        print(letter,end="")

Note that the purpose of "\\n" in the first print is to escape the "\n" character so it will print "\n" instead of printing a linebreak.

  • Related