More on printing and strings

Published

2023-07-31

More on printing strings

Specifying the ending of printed strings

By default, the print() function appends a newline character with each call. Since this is, by far, the most common behavior we desire when printing, this default makes good sense. However, there are times when we do not want this behavior, for example when printing strings that are terminated with newline characters ('\n') as this would produce two newline characters at the end. This happens often when reading certain data from a file. In this case, and in others where we wish to override the default behavior of print(), we can supply the keyword argument, end. The end keyword argument specifies the character (or characters) if any, we wish to append to a printed string.

The .strip() method

Sometimes—especially when reading certain data from a file—we wish to remove whitespace, including spaces, tabs, and newlines from strings. One approach is to use the .strip() method. Without any argument supplied, .strip() removes all leading and trailing whitespace and newlines.

>>> s = '\nHello     \t   \n'
>>> s.strip()
'Hello'

Or you can specify the character you wish to remove.

>>> s = '\nHello     \t   \n'
>>> s.strip('\n')
'Hello     \t   '

This method allows more complex behavior (but I find the use cases rare). For more on .strip() see: https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).