Removing Whitespaces after reading data from File in Python

Removing Whitespaces after reading data from File in Python

read( ), readline( ), readlines( ) functions are used to read data from file. All these functions also read the leading (at beginning) and trailing (at ending) whitespaces  i.e. spaces or tabs or newlines character. If we want to remove these trailing and leading whitespaces, we can use strip( )functions [rstrip( ), lstrip( )] as:

  • strip( ) removes the given character from both ends.
  • rstrip ( ) removes the given character from trailing end e.,right end.
  • lstrip( ) removes the given character from leading end e., left end.

1. Removing EOL ‘\n’ character from the line read from the text file poem.txt

f = file (“poem.txt, “r”)
line =f.readline( )
line = line.rstrip(‘\n’)

2. Removing the leading whitespaces from the line read from the  text file poem.txt.

f = file (“poem.txt, “r”) 
line =f.readline( )
line = line.lstrip( )

3. Removing the leading and trailing whitespaces from the line read from the  text file poem.txt.

f = file (“poem.txt, “r”) 
line =f.readline( )
line = line.strip( )

Spread the love
Lesson tags: Removing the leading and trailing whitespaces, Removing Whitespaces after reading from File
Back to: Python Programming Tutorial
Spread the love