Removing Whitespaces after reading from text file in Python 3

Removing Whitespaces after reading from text file in Python 3

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

Click here for Quiz on Functions in Python

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