Print without a newline or space in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Print without a newline or space in Python #

Use the end and sep arguments of the print() function to print without a newline or space. The end argument can be set to an empty string to print without a newline and the sep argument can be set to an empty string to print without spaces between values.

main.py
# ✅ print without newline print('bobbyhadz', end='') # 👉️ bobbyhadz # ✅ print without spaces print('bobby', 'hadz', '.com', sep='') # 👉️ bobbyhadz.com # ✅ print without newline and spaces print('bobby', 'hadz', sep='', end='') # 👉️ bobbyhadz

The first example uses the end argument to print without a newline (\n) character.

The end argument is printed at the end of the message.

By default, end is set to a newline character (\n).

main.py
for item in ['bobby', 'hadz']: # bobby # hadz print(item) for item in ['bobby', 'hadz']: # bobby hadz print(item, end=' ')

You can set the end argument to an empty string or a string containing a space.

The value of the end argument gets printed immediately after the message you pass to the print() function.

The sep argument is the separator between the arguments we pass to print().

main.py
print('bobby', 'hadz', sep='') # 👉️ bobbyhadz print('bobby', 'hadz') # 👉️ bobby hadz

By default, the sep argument is set to a space.

You can set it to an empty string to print without spaces between the values.

If you have a string that contains newline characters and you need to print it on the same line, use the str.splitlines() method.

main.py
my_str = "bobby\nhadz\n.com" result = my_str.splitlines() print(result) # 👉️ ['bobby', 'hadz', '.com'] for item in result: # 👇️ bobbyhadz.com print(item, end='') result = ''.join(result) print(result) # 👉️ "bobbyhadz.com"

The str.splitlines method splits the string on newline characters and returns a list containing the lines in the string.

The str.splitlines method splits on various line boundaries, e.g. \n, \r, \r\n, etc.

You can use the str.split() method if your string contains whitespace characters and you need to print it without spaces.

main.py
my_str = "bobby hadz .com" result = my_str.split() print(result) # 👉️ ['bobby', 'hadz', '.com'] for item in result: # 👇️ bobbyhadz.com print(item, end='') result = ''.join(result) print(result) # 👉️ "bobbyhadz.com"

The str.split() method splits the string into a list of substrings using a delimiter.

When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.