Python Forum

Full Version: Inserting carriage return to string.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
string='This is sentence 1.Ths is sentence 2.'
print(string) produces: This is sentence 1.This is sentence 2.

However, I'd like to print the string as separate lines.  To do so I add what I believe are carriage returns as follows:

string=This is sentence 1.\nThs is sentence 2.\n
print(string) produces:

This is sentence 1.
Ths is sentence 2.

That's what I want.  But why does a loop print letter-by-letter?  It seems it should also print everything up \n on one line.

for i in string:
 print(i)

T
h
i
s

i
s

s
e
n
t
e
n
c
e

1
.


T
h
i
s

i
s

s
e
n
t
e
n
c
e

2
.
Because you loop over each element of an iterable and print it. In this case, this is a string. A print function adds a new line character at the end.
Just print it
>>> string="This is sentence 1.\nThs is sentence 2.\n"
>>> print(string)
This is sentence 1.
Ths is sentence 2.