How to print without a newline or space in Python ?

To print without a newline or space in Python, use the following methods depending on your Python version and requirements:

1. In Python 3+

Use the print() function with the end and sep parameters.

Print Without a Newline:

print("Hello", end="")  # No newline
print("World")          # Output: HelloWorld

Print Multiple Items Without Spaces:

print("a", "b", "c", sep="")  # Output: abc

Combine Both:

print("Hello", "World", sep="", end="")  # Output: HelloWorld (no newline or space)

2. In Python 2

Use a trailing comma in the print statement (adds a space by default) or use sys.stdout.write.

Avoid Newline (Adds Space):

print "Hello",  # Trailing comma
print "World"   # Output: Hello World

Avoid Newline and Space:

import sys
sys.stdout.write("Hello")
sys.stdout.write("World")  # Output: HelloWorld

3. Universal Approach (Works in Both Python 2 and 3)

Use sys.stdout.write for full control:

import sys
sys.stdout.write("Hello")
sys.stdout.write("World\n")  # Output: HelloWorld

Examples

Print a List Without Newlines:

# Python 3
items = [1, 2, 3]
for item in items:
    print(item, end="")  # Output: 123

# Python 2
for item in items:
    print item,           # Output: 1 2 3 (with spaces)

Print with Custom Separator:

# Python 3
print("2023", "12", "31", sep="-")  # Output: 2023-12-31

Key Notes

  • end Parameter: Controls the ending character (default: \n).
  • sep Parameter: Controls the separator between items (default: space).
  • sys.stdout.write: Directly writes to output without formatting.
  • Flushing: Use sys.stdout.flush() to force immediate output if needed.

Summary

  • Python 3: Use print(..., end="", sep="").
  • Python 2: Use sys.stdout.write() or print ..., (with a trailing comma for no newline).
  • Cross-version: sys.stdout.write() works everywhere but lacks formatting.

Leave a Reply

Your email address will not be published. Required fields are marked *