Today we’ll be talking about the print function, and to be precise, we’ll see how to print strings without the newline character at the end, which is possible if you explicitly use the end parameter in the print function.
When you use the print function, a newline is appended to the string:
titles = ['Sponge Girl',
'Headless Statues',
'Bill the Catfish',
'Bang']
for title in titles:
print(title)
The output:
Sponge Girl
Headless Statues
Bill the Catfish
Bang
So, each string is on a separate line. This is because the print function takes an optional end parameter, which defaults to the newline character. But you can change it to anything else.
The end Parameter
So, as mentioned above the default value assigned to the end parameter is ‘\n’, so the newline character. However, if you explicitly set it to a different string, this string will be used instead of the newline character.
Here are some examples:
1) Put a white space at the end of the string:
titles = ['Sponge Girl',
'Headless Statues',
'Bill the Catfish',
'Bang']
for title in titles:
print(title, end = " ") # whitespace added at the end
The output is:
Sponge Girl Headless Statues Bill the Catfish Bang
2) Put an asterisk surrounded by white spaces at the end of the string:
titles = ['Sponge Girl',
'Headless Statues',
'Bill the Catfish',
'Bang']
for title in titles:
print(title, end = " * ")
The output is:
Sponge Girl * Headless Statues * Bill the Catfish * Bang *
3) Put a tab at the end of the string:
titles = ['Sponge Girl',
'Headless Statues',
'Bill the Catfish',
'Bang']
for title in titles:
print(title, end = "\t") # a tab added
The output is:
Sponge Girl Headless Statues Bill the Catfish Bang
4) Put an arbitrary sequence of characters plus a newline character at the end of the string:
titles = ['Sponge Girl',
'Headless Statues',
'Bill the Catfish',
'Bang']
for title in titles:
print(title, end = "###\n") # hash + newline
The output is:
Sponge Girl###
Headless Statues###
Bill the Catfish###
Bang###
5) Don’t put anything at the end of the string:
titles = ['Sponge Girl',
'Headless Statues',
'Bill the Catfish',
'Bang']
for title in titles:
print(title, end = "") # nothing
The output is:
Sponge GirlHeadless StatuesBill the CatfishBang
6) You can even use a formatted string as the end parameter:
titles = ['Sponge Girl',
'Headless Statues',
'Bill the Catfish',
'Bang']
for title in titles:
print(title, end = f" -> ({titles.index(title)}) ")
The output is:
Sponge Girl -> (0) Headless Statues -> (1) Bill the Catfish -> (2) Bang -> (3)
You can experiment yourself, but usually the parameter is set to something simple and we use different ways of formatting text.
Here’s the video version: