Bottom Page

Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Inserting carriage return to string.
#1
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
.
Quote
#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.

"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  How to Save Full Email Body to CLOB in Oracle w/Carriage Returns? bmccollum 1 227 Mar-12-2020, 10:25 PM
Last Post: Larz60+
  Problem with inserting a string in to Sqlite db darktitan 3 702 Mar-03-2019, 06:30 PM
Last Post: stranac
  script: remove all "carriage return" from my json variable mfran2002 4 2,235 Feb-20-2019, 05:07 AM
Last Post: mfran2002
  How to return a standard output instead of string kavindu 1 666 Oct-28-2018, 01:09 PM
Last Post: ichabod801
  Return string from Javascript ian 0 816 Feb-11-2018, 04:41 PM
Last Post: ian

Forum Jump:


Users browsing this thread: 1 Guest(s)