Как убрать n python при чтении из файла
Перейти к содержимому

Как убрать n python при чтении из файла

  • автор:

Как убрать символ новой строки (\n) при чтении строк из файла

При использовании file.readlines() получаем что-то вроде этого:

Если хочется поддерживать и Юникодные окончания строк, то можно str.splitlines() метод использовать:

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.6.8.43486

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Read a File Without Newlines in Python

Read a File Without Newlines in Python

File handling such as editing a file, opening a file, and reading a file can easily be carried out in Python. Reading a file in Python is a very common task that any user performs before making any changes to the file.

While reading the file, the new line character \n is used to denote the end of a file and the beginning of the next line. This tutorial will demonstrate how to readline without a newline in Python.

Use the strip() and the rstrip() Methods to Read a Line Without a Newline in Python

The strip() method in Python helps in omitting the spaces that are present at the beginning (leading) and at the end (trailing). Besides white spaces, the strip() method also includes the newline characters.

Here’s an example you can follow.

The open() is used to open the file. Note that the strip() method will get rid of the newline and the whitespaces at the beginning and the end in the example above. To keep the whitespaces and just omit the newline, the \n command is passed as an argument or a parameter to the strip() method.

We can also use the rstrip() method because the strip() method omits both the leading and the trailing spaces. On the other hand, the rstrip() method just removes the trailing spaces or characters. This method is useful because the newline is present at the end of every string. We can also mention the newline character by \n .

Follow this example below.

Use the splitlines and the split() Methods to Read a Line Without a Newline in Python

The splitlines() method in Python helps split a set of strings into a list. Each string in the set of the string is an element of the list. Thus, the splitlines() method splits the string wherever the newline is present.

Python Remove Newline From String

There are times where we need to remove the newline from string while processing massive data. This tutorial will learn different approaches to strip newline characters from string in Python.

Python Remove Newline From String

In Python new line character is represented with “ \n .” Python’s print statement by default adds the newline character at the end of the string.

There are 3 different methods to remove the newline characters from the string.

  1. strip() method
  2. replace() method
  3. re.sub() method

Using strip() method to remove the newline character from a string

The strip() method will remove both trailing and leading newlines from the string. It also removes any whitespaces on both sides of a string.

Output

If the newline is at the end of the string, you could use the rstrip() method to remove a trailing newline characters from a string, as shown below.

Output

Using replace() method to remove newlines from a string

The replace() function is a built-in method, and it will replace the specified character with another character in a given string.

In the below code, we are using replace() function to replace the newline characters in a given string. The replace() function will replace the old character and substitute it with an empty one.

Similarly, if we need to replace inside newline characters in a list of strings, we can iterate it through for loop and use a replace() function to remove the newline characters.

Output

We can also use the map function in Python to iterate the list of strings and remove the newline characters, as shown below. It would be a more optimized and efficient way of coding when compared to the for a loop.

Output

Using regex to remove newline character from string

Another approach is to use the regular expression functions in Python to replace the newline characters with an empty string. The regex approach can be used to remove all the occurrences of the newlines in a given string.

The re.sub() function is similar to replace() method in Python. The re.sub() function will replace the specified newline character with an empty character.

Output

Ezoic

report this ad

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *