How to Print Without a Newline or Space

When using the print function in Python, a newline character (\n) is automatically added at the end of each printed statement. Additionally, a space is added as a separator between multiple values passed to the print function.

However, there are cases where you may want to print values without a newline or space between them. This article will discuss various techniques to achieve this in Python.

Method 1: Using the end parameter in print

The easiest way to print without a newline or space is by using the end parameter in the print function. By default, the value of the end parameter is set to '\n', which adds a newline character at the end.

print('.', end='')
print('.', end='')
print('.', end='')
print('.', end='')

The above code will output .... without any newline or space between each dot.

Method 2: Using the sep parameter in print

If you want to print multiple values without a space between them, you can use the sep parameter in the print function. By default, the value of the sep parameter is set to ' ', which adds a space between each value.

print('.', '.', '.', '.', sep='')

The above code will output .... without any space between each dot.

Method 3: Using string concatenation or formatting

Another way to achieve the desired output is by string concatenation or formatting. Instead of using the print function directly, you can create one string that combines all the values you want to print without any separators.

output = '.' * 4
print(output)

The above code will output .... by concatenating four dots using the string multiplication operator (*)

output = '{}{}{}{}'.format('.', '.', '.', '.')
print(output)

The above code will also output .... by formatting four dots into a single string.

Method 4: Using sys.stdout

If you need more control over the standard output stream, you can use the sys.stdout.write() function from the sys module. This function allows you to write directly to stdout without adding a newline or space.

import sys
sys.stdout.write('.')
sys.stdout.write('.')
sys.stdout.write('.')
sys.stdout.write('.')

This code will output .... without any newline or space between each dot.

Summary

In summary, there are multiple ways to print without a newline or space in Python:

  • Using the end parameter in the print function
  • Using the sep parameter in the print function
  • Using string concatenation or formatting
  • Using the sys.stdout.write() function

Choose the method that best suits your needs and preferences.