Python string with new lines

Handle line breaks (newlines) in strings in Python

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

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 # Line3 s = '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 «»» .

s = '''Line1 Line2 Line3''' 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:

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 # Line3 s = ('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 = '''\ Line1 Line2 Line3''' print(s) # Line1 # Line2 # Line3 s = '''\ 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() .

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 # Line3 print(repr(s_n)) # 'Line1\nLine2\nLine3' s_rn = '\r\n'.join(l) print(s_rn) # Line1 # Line2 # Line3 print(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() .

Читайте также:  Php session unset не работает

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() .

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())) # Line1Line2Line3 print(' '.join(s.splitlines())) # Line1 Line2 Line3 print(','.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 # Line3 print(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() .

s = 'Line1\nLine2\nLine3' print(s.replace('\n', '')) # Line1Line2Line3 print(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) # ,Line3Line2 print(repr(s_error)) # 'Line1,Line2\r,Line3' s_error = s.replace('\r\n', ',') print(s_error) # Line1 # Line2,Line3 print(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,Line3 s_error = s.replace('\n', ',').replace('\r\n', ',') print(s_error) # ,Line3Line2 print(repr(s_error)) # 'Line1,Line2\r,Line3' print(','.join(s.splitlines())) # Line1,Line2,Line3 

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

s = 'aaa\n' print(s + 'bbb') # aaa # bbb print(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’ .

Читайте также:  Определить дату рождения php

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.

Источник

Python New Line and How to Print Without Newline

Python New Lines and How to Print Without Newline Cover image

In this tutorial, you’ll learn how to use the Python new line character and how to print without newlines. Being able to control how your program prints strings is an important skill, especially when working with text files or command-line interfaces (CLIs). In this tutorial, you’ll learn different ways to include a newline character in your Python program, including the \n character and multi-line strings.

Being able to print across new lines increases the readability of your program’s output. Similarly, newline characters are often found in text files. Being able to understand how these characters work in Python will allow you to create programs that respond how you expect them to.

By the end of this tutorial, you’ll have learned:

  • What the Python new line character is
  • How to print without newlines in Python
  • How to use multiline strings to print across multiple lines

Python Newline Character

In Python, the character to create a new line is the \n character. Wherever this character is inserted into a string, a new line will be created when the string is printed out. In essence, this character indicates where a line ends – any further characters will be printed on a new line.

Let’s take a look at an example of how you can use the Python newline character, \n , to print on multiple lines in Python:

# Printing on Multiple Lines in Python string = "Welcome to datagy!\nLearn Python and Data Science!" print(string) # Returns: # Welcome to datagy! # Learn Python and Data Science!

We can see that by including the \n newline character, that when the string was printed the text was split across multiple lines.

As a fun aside, you may be thinking, “what if I actually want to print ‘\n’ ?” Thankfully, this is very simple to do! The \ character acts as the escape character. By prefixing this to the newline character, the newline character will be escaped. Let’s see what this looks like:

# Escaping the Newline Character in Python string = "Welcome to datagy!\\nLearn Python and Data Science!" print(string) # Returns: # Welcome to datagy!\nLearn Python and Data Science!

We can see that the escape character isn’t printed, but that the newline character is printed in full.

Читайте также:  line-height

Printing in Python Without Newlines

When you print multiple statements in Python, by default they print across multiple lines. Take a look at the code below as an example:

# Printing Multiple Statements in Python print("Hello!") print("Welcome to datagy!") # Returns: # Hello! # Welcome to datagy!

The reason that these statements print across different lines is because the print() function has a parameter end= which defaults to the newline character, ‘\n’ .

We can actually change the ending of these print statements by passing in a different string. For example, if we wanted to keep printing multiple statements on the same output line, we could simply write:

# Printing in Python Without Newlines print("Hello!", end=' ') print("Welcome to datagy!") # Returns: # Hello! Welcome to datagy!

In the example above, we modified the end= parameter to simply be a space character. Because of this, the two statements were printed on the same line, separated only by a single space.

Newlines in Python Multiline Strings

Another way in which you can easily print across multiple lines in Python is to use multi-line strings. Multi-line strings in Python are declared by triple single quotes or triple double quotes. This allows you to use line breaks within the string without explicitly declaring them.

Let’s take a look at how we can replicate our earlier example using multi-line strings:

# Printing on Multiple Lines in Python string = """Hello! Welcome to datagy!""" print(string) # Returns: # Hello! # Welcome to datagy!

Because we declared the string as a multi-line string, we were able to handle the linebreaks implicitly!

How to Remove New Lines in Python

We can use various string methods to remove leading and trailing newline characters. The .rstrip() and .lstrip() methods to remove leading and trailing whitespace (including newline characters) respectively. Let’s see how we can use the .lstrip() method to remove a leading newline character:

# Removing a Trailing Newline Character in Python string = "\nHello! Welcome to datagy!" print(string) print(string.lstrip()) # Returns: # # Hello! Welcome to datagy! # Hello! Welcome to datagy!

In the example, we first printed the string with the leading newline character. Then, we printed the line by left stripping out any whitespace.

Conclusion

In this tutorial, you learned how to work with the newline character in Python. You learned how the new line character works, how to escape the new line character and how to print without the default new line argument. Then, you learned how to use multi-line strings to emulate printing on new lines. Finally, you learned how to remove new lines from strings in Python.

Additional Resources

To learn about related topics, check out the tutorials below:

Источник

Оцените статью