Replace new lines in python

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:

Читайте также:  Header in php with parameters

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

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’ .

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: Remove Newline Character from String

Python Remove Newline Characters from String Cover Image

In this tutorial, you’ll learn how to use Python to remove newline characters from a string.

Working with strings in Python can be a difficult game, that often comes with a lot of pre-processing of data. Since the strings we find online often come with many issues, learning how to clean your strings can save you a lot of time. One common issue you’ll encounter is additional newline characters in strings that can cause issues in your work.

The Quick Answer: Use Python string.replace()

Quick Answer - Python Remove Newline Characters

What are Python Newline Characters

Python comes with special characters to let the computer know to insert a new line. These characters are called newline characters. These characters look like this: \n .

When you have a string that includes this character, the text following the newline character will be printed on a new line.

Let’s see how this looks in practice:

a_string = 'Hello!\nWelcome to Datagy!\nHow are you?\n' print(a_string) # Returns # Hello! # Welcome to Datagy! # How are you?

Now that you know how newline characters work in Python, let’s learn how you can remove them!

Use Python to Remove All Newline Characters from a String

Python’s strings come built in with a number of useful methods. One of these is the .replace() method, which does exactly what it describes: it allows you to replace parts of a string.

# Use string.replace() to replace newline characters in a string a_string = 'Hello!\n Welcome to Datagy!\n How are you?\n' a_string = a_string.replace('\n','') print(a_string) # Returns: Hello! Welcome to Datagy! How are you?

Let’s see what we’ve done here:

  1. We passed the string.replace() method onto our string
  2. As parameters, the first positional argument indicates what string we want to replace. Here, we specified the newline \n character.
  3. The second argument indicates what to replace that character with. In this case, we replaced it with nothing, thereby removing the character.

In this section, you learned how to use string.replace() to remove newline characters from a Python string. In the next section, you’ll learn how to replace trailing newlines.

Tip! If you want to learn more about how to use the .replace() method, check out my in-depth guide here.

Use Python to Remove Trailing Newline Characters from a String

There may be times in your text pre-processing that you don’t want to remove all newline characters, but only want to remove trailing newline characters in Python. In these cases, the .replace() method isn’t ideal. Thankfully, Python comes with a different string method that allows us to to strip characters from the trailing end of a string: the .rstrip() method.

Let’s dive into how this method works in practise:

# Remove trailing newline characters from a string in Python a_string = 'Hello! \nWelcome to Datagy! \nHow are you?\n' a_string = a_string.rstrip() print(a_string) # Returns # Hello! # Welcome to Datagy! # How are you?

The Python .rstrip() method works by removing any whitespace characters from the string. Because of this, we didn’t need to specify a new line character.

If you only wanted to remove newline characters, you could simply specify this, letting Python know to keep any other whitespace characters in the string. This would look like the line below:

a_string = a_string.rstrip('\n')

In the next section, you’ll learn how to use regex to remove newline characters from a string in Python.

Tip! If you want to learn more about the .rstrip() (as well as the .lstrip() ) method in Python, check out my in-depth tutorial here.

Use Python Regex to Remove Newline Characters from a String

Python’s built-in regular expression library, re , is a very powerful tool to allow you to work with strings and manipulate them in creative ways. One of the things we can use regular expressions (regex) for, is to remove newline characters in a Python string.

Let’s see how we can do this:

# Use regular expressions to remove newline characters from a string in Python import re a_string = 'Hello! \nWelcome to Datagy! \nHow are you?\n' a_string = re.sub('\n', '', a_string) print(a_string) # Returns: Hello! Welcome to Datagy! How are you?

Let’s see what we’ve done here:

  1. We imported re to allow us to use the regex library
  2. We use the re.sub() function, to which we passed three parameters: (1) the string we want to replace, (2), the string we want to replace it with, and (3) the string on which the replacement is to be done

It may seem overkill to use re for this, and it often is, but if you’re importing re anyway, you may as well use this approach, as it lets you do much more complex removals!

Conclusion

In this post, you learned how to use Python to remove newline characters from a string. You learned how to do this using the string.replace() method, how to replace trailing newlines using .rstrip() , and how to accomplish this using regular expression’s sub() function.

Additional Resources

To learn more about related topics, check out the resources below:

Источник

Python: Various methods to remove the newlines from a text file

The ‘\n’ character represents the new line in python programming. However, this tutorial will show you various methods to remove the newlines from a text file.

Before starting, let us see the output of our file, which we want to remove all newlines from it.

Note: I’ve used the repr() function to print the file’s output with the ‘\n’ character.

Method #1: Remove newlines from a file using replace()

the replace() method replaces a specified phrase with another specified phrase. Therefore, we’ll use this method to replace the newline character with a non-value.

Syntax

Example

method #2: Remove newlines from a file using splitlines()

The splitlines() method splits a string at the newline break and returns the result as a list.

However, we will use the splitlines() to split the file’s output at ‘\n’ and the join() method to join the result.

Syntax

Method #3: Remove newlines from a file using Regex

We can also use the re.sub() function to remove the newlines from a text file.

Syntax

The sub() function works like replace() function.

Example

Conclusion

We’ve learned different methods to remove the newlines from a text file in this article. Moreover, if you want to remove the newlines from the beginning or end of the text file, you should use strip() and rstrip() methods.

Источник

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