str.rstrip() returns a new string with trailing whitespace removed. It is especially useful for removing the newline commonly left at the end of text read from a file. section 5.1 section 7.3.2
Use rstrip() to normalize text at input boundaries:
- Chain it after reading a complete file: open(file).read().rstrip(). section 5.5.2
- Apply it to each line before storing or processing that line. section 7.3.2
- Keep the original string unchanged; the method returns a cleaned copy. section 5.5.2
Remove a file's final newline
>>> text = open(file).read().rstrip() >>> text 'The quick brown fox jumps over the lazy dog.' For line-oriented input, the same operation appears as line.rstrip(), leaving the line's content without its trailing whitespace. section 5.1 section 7.3.2
Figure 5.6 The open() function returns a file handle (fh). The fh.read() function returns a str. The str.rstrip() function returns a new str with the whitespace removed from the right side. All these functions can be chained together.
Trace the chained pipeline from open() to read() to rstrip(), including the changing value type at each step. section 5.5.2
