Handle line breaks (newlines) in strings in Python | note.nkmk.me (2024)

This article explains how to handle strings including line breaks (line feeds, new lines) in Python.

Contents

  • Create a string containing line breaks
    • Newline character \n (LF), \r\n (CR + LF)
    • Triple quote ''', """
    • With indent
  • Concatenate a list of strings on new lines
  • Split a string into a list by line breaks: splitlines()
  • Remove or replace line breaks
  • Output with print() without a trailing newline

Create a string containing line breaks

Newline character \n (LF), \r\n (CR + LF)

To create a line break at a specific location in a string, insert a newline character, either \n or \r\n.

s = 'Line1\nLine2\nLine3'print(s)# Line1# Line2# Line3s = 'Line1\r\nLine2\r\nLine3'print(s)# Line1# Line2# Line3

On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline character. Some text editors allow you to select a newline character.

Triple quote ''', """

You can write a string including line breaks with triple quotes, either ''' or """.

  • Create a string in Python (single/double/triple quotes, str())
s = '''Line1Line2Line3'''print(s)# Line1# Line2# Line3

With indent

Using triple quotes with indentation could insert unnecessary spaces, as demonstrated below.

s = ''' Line1 Line2 Line3 '''print(s)# # Line1# Line2# Line3# 

By enclosing each line in '' or "", adding a line break \n at the end, and using a backslash \ to continue the line, you can write the string as follows:

s = 'Line1\n'\ 'Line2\n'\ 'Line3'print(s)# Line1# Line2# Line3

This approach uses a mechanism in which consecutive string literals are concatenated. See the following article for details:

  • Concatenate strings in Python (+ operator, join, etc.)

If you want to add indentation in the string, add a space to the string on each line.

s = 'Line1\n'\ ' Line2\n'\ ' Line3'print(s)# Line1# Line2# Line3

Since you can freely break lines within parentheses (), you can also write the string inside them without using backslashes \.

s = ('Line1\n' 'Line2\n' 'Line3')print(s)# Line1# Line2# Line3s = ('Line1\n' ' Line2\n' ' Line3')print(s)# Line1# Line2# Line3

If you want to align the beginning of a line, you can add a backslash \ to the first line of triple quotes.

s = '''\Line1Line2Line3'''print(s)# Line1# Line2# Line3s = '''\Line1 Line2 Line3'''print(s)# Line1# Line2# Line3

Concatenate a list of strings on new lines

You can concatenate a list of strings into a single string with the string method join().

  • Concatenate strings in Python (+ operator, join, etc.)

By calling join() from a newline character, either \n or \r\n, each element will be concatenated on new lines.

l = ['Line1', 'Line2', 'Line3']s_n = '\n'.join(l)print(s_n)# Line1# Line2# Line3print(repr(s_n))# 'Line1\nLine2\nLine3's_rn = '\r\n'.join(l)print(s_rn)# Line1# Line2# Line3print(repr(s_rn))# 'Line1\r\nLine2\r\nLine3'

As shown in the example above, you can check the string with newline characters intact using the built-in function repr().

Split a string into a list by line breaks: splitlines()

You can split a string by line breaks into a list with the string method, splitlines().

s = 'Line1\nLine2\r\nLine3'print(s.splitlines())# ['Line1', 'Line2', 'Line3']

In addition to \n and \r\n, the string is also split by other newline characters such as \v (line tabulation) or \f (form feed).

See also the following article for more information on splitlines().

  • Split a string in Python (delimiter, line break, regex, and more)

Remove or replace line breaks

Using splitlines() and join(), you can remove newline characters from a string or replace them with another string.

s = 'Line1\nLine2\r\nLine3'print(''.join(s.splitlines()))# Line1Line2Line3print(' '.join(s.splitlines()))# Line1 Line2 Line3print(','.join(s.splitlines()))# Line1,Line2,Line3

It is also possible to change the newline character all at once. Even if the newline character is mixed or unknown, you can split the string with splitlines() and then concatenate the lines with the desired character.

s_n = '\n'.join(s.splitlines())print(s_n)# Line1# Line2# Line3print(repr(s_n))# 'Line1\nLine2\nLine3'

Since splitlines() splits both \n (LF) and \r\n (CR + LF), as mentioned above, you don't have to worry about which newline character is used in the string.

You can also replace the newline character with replace().

  • Replace strings in Python (replace, translate, re.sub, re.subn)
s = 'Line1\nLine2\nLine3'print(s.replace('\n', ''))# Line1Line2Line3print(s.replace('\n', ','))# Line1,Line2,Line3

However, be aware that it will not work if the string contains a different newline character than expected.

s = 'Line1\nLine2\r\nLine3's_error = s.replace('\n', ',')print(s_error)# ,Line3Line2print(repr(s_error))# 'Line1,Line2\r,Line3's_error = s.replace('\r\n', ',')print(s_error)# Line1# Line2,Line3print(repr(s_error))# 'Line1\nLine2,Line3'

You can use replace() multiple times to replace various newline characters, but since \r\n contains \n, it may not work correctly if done in the wrong order. As mentioned above, using splitlines() and join() is a safer approach, as you don't have to worry about the specific line feed characters being used.

s = 'Line1\nLine2\r\nLine3'print(s.replace('\r\n', ',').replace('\n', ','))# Line1,Line2,Line3s_error = s.replace('\n', ',').replace('\r\n', ',')print(s_error)# ,Line3Line2print(repr(s_error))# 'Line1,Line2\r,Line3'print(','.join(s.splitlines()))# Line1,Line2,Line3

You can use rstrip() to remove trailing newline characters.

  • Remove a substring from a string in Python
s = 'aaa\n'print(s + 'bbb')# aaa# bbbprint(s.rstrip() + 'bbb')# aaabbb

Output with print() without a trailing newline

By default, print() adds a newline at the end. Therefore, if you execute print() continuously, each output result will be displayed with a line break.

print('a')print('b')print('c')# a# b# c

This is because the default value of the end argument of print(), which specifies the string to be added at the end, is '\n'.

If the empty string '' is specified in end, a line break will not occur at the end.

print('a', end='')print('b', end='')print('c', end='')# abc

Any string can be specified in end.

print('a', end='-')print('b', end='-')print('c')# a-b-c

However, if you want to concatenate strings and output them, it's more straightforward to concatenate the original strings directly. See the following article.

  • Concatenate strings in Python (+ operator, join, etc.)
Handle line breaks (newlines) in strings in Python | note.nkmk.me (2024)
Top Articles
40+ MIND Diet Recipes & a Free Meal Plan for Better Brain Health
Carnivore Recipes: 25 Delicious Carnivore Meals! | Healthy Ambitions
Kem Minnick Playboy
Avonlea Havanese
Workday Latech Edu
Kansas Craigslist Free Stuff
Holly Ranch Aussie Farm
35105N Sap 5 50 W Nit
Mr Tire Rockland Maine
Www.paystubportal.com/7-11 Login
Lesson 2 Homework 4.1
Raid Guides - Hardstuck
Knaben Pirate Download
Inside California's brutal underground market for puppies: Neglected dogs, deceived owners, big profits
Robert Malone é o inventor da vacina mRNA e está certo sobre vacinação de crianças #boato
Sarpian Cat
Costco Gas Foster City
Nalley Tartar Sauce
Plan Z - Nazi Shipbuilding Plans
Tamilyogi Proxy
Amazing deals for Abercrombie & Fitch Co. on Goodshop!
Samantha Aufderheide
Marine Forecast Sandy Hook To Manasquan Inlet
Vegito Clothes Xenoverse 2
Where to eat: the 50 best restaurants in Freiburg im Breisgau
Encyclopaedia Metallum - WikiMili, The Best Wikipedia Reader
Southland Goldendoodles
Lines Ac And Rs Can Best Be Described As
Walgreens On Bingle And Long Point
Account Now Login In
2023 Ford Bronco Raptor for sale - Dallas, TX - craigslist
The Monitor Recent Obituaries: All Of The Monitor's Recent Obituaries
Desales Field Hockey Schedule
Tmj4 Weather Milwaukee
Marine Forecast Sandy Hook To Manasquan Inlet
The 38 Best Restaurants in Montreal
Are you ready for some football? Zag Alum Justin Lange Forges Career in NFL
ATM Near Me | Find The Nearest ATM Location | ATM Locator NL
1v1.LOL Game [Unblocked] | Play Online
Top 40 Minecraft mods to enhance your gaming experience
Brake Pads - The Best Front and Rear Brake Pads for Cars, Trucks & SUVs | AutoZone
Erica Mena Net Worth Forbes
Zadruga Elita 7 Live - Zadruga Elita 8 Uživo HD Emitirani Sat Putem Interneta
Msatlantathickdream
Concentrix + Webhelp devient Concentrix
Diccionario De Los Sueños Misabueso
Assignation en paiement ou injonction de payer ?
2000 Fortnite Symbols
Okta Hendrick Login
Rise Meadville Reviews
Bunbrat
Latest Posts
Article information

Author: Ray Christiansen

Last Updated:

Views: 5916

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.