More on printing and strings
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:
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.