Python Forum
Inserting carriage return to string.
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
.
Reply
#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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Inserting line feeds and comments into a beautifulsoup string arbiel 1 1,182 Jul-20-2022, 09:05 AM
Last Post: arbiel
  Regular expression: return string, not list Pavel_47 3 2,490 Jan-14-2021, 11:49 AM
Last Post: Pavel_47
  Getting Shell to take prompt string plus int value and carriage return bayouprophet 1 1,748 Aug-29-2020, 05:13 PM
Last Post: bowlofred
  return string from function with one argument jamie_01 2 2,181 May-28-2020, 11:07 PM
Last Post: menator01
  [split] script: remove all "carriage return" from my json variable pete 2 2,786 May-05-2020, 03:22 PM
Last Post: deanhystad
  How to Save Full Email Body to CLOB in Oracle w/Carriage Returns? bmccollum 1 2,278 Mar-12-2020, 10:25 PM
Last Post: Larz60+
  Problem with inserting a string in to Sqlite db darktitan 3 4,491 Mar-03-2019, 06:30 PM
Last Post: stranac
  script: remove all "carriage return" from my json variable mfran2002 4 11,178 Feb-20-2019, 05:07 AM
Last Post: mfran2002
  How to return a standard output instead of string kavindu 1 2,517 Oct-28-2018, 01:09 PM
Last Post: ichabod801
  Return string from Javascript ian 0 2,278 Feb-11-2018, 04:41 PM
Last Post: ian

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020