Python - How To Remove Trailing Whitespaces in a Python String

ID : 31

viewed : 258

Tags : PythonPython String

vote vote

97

In Python, whitespaces are generally used to separate and create code blocks.

However, whitespaces may also come about in unexpected areas, necessitating their removal.

txt = "  string   "   print(txt.strip()) 

Output:

string 

Whitespaces may also exist at the beginning or end of a string; whitespaces at the end of a string are trailing whitespaces, while those at the beginning of a string are leading whitespaces. Removing whitespaces is generally easy since Python provides the strip() method that removes trailing and leading whitespaces.

Removing Trailing Whitespaces Using the rstrip() Method in Python

While the code snippet above is pretty straightforward, this may not always be the case.

Suppose the data that contains whitespaces exists in another file, then we are forced to use another script to try and remove the whitespaces. Therefore we will need to create a script that reads the contents of the external file to modify it.

Generally, Python provides two ways that we can exploit to read the contents of an external file.

The key function for reading and opening external files in Python is the open() function that takes in two parameters: the file name and the mode. Although the open() function returns a file object using the read() method, we can read the exact number of bytes that we want from the external file.

Using the rstrip(), we can remove the trailing whitespaces, shown in the code snippet below.

with open("sample.txt")as f:     for line in f:         line = line.rstrip()         if line:             print(line) 

sample.txt:

    Mango         Oranges         Apple         Pawpaw     

Output:

    Mango     Oranges     Apple     Pawpaw 

In the code snippet above, we have managed to remove the whitespaces on the right-hand side of the strings, also known as the trailing whitespaces, using a Python script external to the text file. On the other hand, leading whitespaces can also be removed using the lstrip() method.

f = open("sample.txt") for line in f:         line = line.lstrip()         if line:             print(line)   f.close() 

Output:

Mango     Oranges     Apple     Pawpaw     

Alternatively, we can also write a loop over any list of values using the standard fileinput provided by Python. By default, the fileinput module allows us to open the file inputs in text mode and ensure the empty files are closed immediately.

Furthermore, the module also gives us the freedom to specify hooks which is a function that takes in the name of the file and the mode that we want to access the file as the two major parameters.

Using the fileinput.FileInput() class, we can also create an instance that can be used alongside the context manager. This ensures that if an exception occurs during the performing file operations, the program does not exit prematurely without closing files that we may have already opened.

import fileinput  filename = r"C:\test\sample.txt"  with fileinput.FileInput(filename,                          inplace = False) as f:       for line in f:         line = line.rstrip()         if line:             print(line) 

Output:

    Mango     Oranges     Apple     Pawpaw 

Although the fileinput module is used to iterate over multiple input streams, we have used the module alongside the fileinput.FileInput() class and the context manager to create an immediately exited instance outside the with statement. We performed an iteration over the text file using the’ for’ loop and applied the rsplit() method.

The fileinput.FileInput() class also accepts several parameters, such as the file name and the mode in which we intend to open the file. In this case, we have only specified three parameters, including setting the inplace modification to False since we do not intend to perform any inplace editing of the file.

  • Related HOW TO?