How to print without spaces in Python
Learn how to print in Python without spaces. Discover different methods, tips, real-world applications, and how to debug common errors.

Python's print() function automatically adds a space between items. While useful, you often need to print strings or variables without this default separator for cleaner output and specific formatting.
In this guide, you'll explore techniques like the sep parameter and string concatenation. You'll also find real-world applications and debugging tips to help you master output formatting in your projects.
Basic printing without spaces using end=''
for i in range(5):
print(i, end='')
print() # Add a newline at the end--OUTPUT--1234
The print() function typically adds a newline after its output. In this loop, setting end='' overrides that default behavior. Instead of a newline, an empty string is appended, causing each number to be printed immediately after the previous one on the same line.
This technique is useful when you're building output iteratively. Each call to print(i, end='') adds the next digit without any separating characters. The final, empty print() call simply moves the cursor to the next line for a clean finish.
Alternative printing approaches
Beyond the end='' trick, you can also control spacing with string concatenation, the print() function's sep parameter, and various string formatting methods.
Using string concatenation
words = ["Hello", "World", "Python"]
result = ''.join(words)
print(result)--OUTPUT--HelloWorldPython
String concatenation offers another way to control output. The join() method is particularly powerful for this. It's called on a separator string—in this case, an empty string ''—and merges all items from an iterable, like the words list, into one.
- The
''before.join()ensures no characters are inserted between elements. - This method is efficient for combining many strings without unwanted spaces.
The final result is a single, continuous string, which is then printed to the console.
Using the sep parameter with print()
a, b, c = "No", "Space", "Here"
print(a, b, c, sep='')--OUTPUT--NoSpaceHere
The print() function's sep parameter gives you direct control over the spacing between items. While print() normally inserts a space, you can easily change this behavior.
- By setting
sep='', you're telling Python to use an empty string as the separator. - This causes the arguments—
a,b, andc—to be printed right next to each other.
It's a clean and direct method for joining multiple variables in your output without any extra characters.
Using string formatting methods
items = ['apple', 'banana', 'cherry']
formatted = f"{items[0]}{items[1]}{items[2]}"
print(formatted)--OUTPUT--applebananacherry
F-strings, or formatted string literals, offer a modern and highly readable way to build strings. You can embed expressions directly inside a string by placing them in curly braces {}.
- The expression
f"{items[0]}{items[1]}{items[2]}"accesses each list item by its index. - Since there are no spaces between the curly braces in the f-string, the elements are joined seamlessly.
This method gives you full control over the output, making it easy to create precisely formatted strings without any extra characters.
Advanced techniques
For situations requiring more finesse, you can combine join() with list comprehensions, build a custom print function, or write directly to the sys.stdout stream.
Using list comprehension with join()
numbers = [1, 2, 3, 4, 5]
result = ''.join([str(num) for num in numbers])
print(result)--OUTPUT--12345
This method is perfect when your list contains non-string items like numbers. The join() function requires strings, so you can't use it directly on a list of integers. That's where the list comprehension comes in.
- The expression
[str(num) for num in numbers]iterates through your list and converts each number to a string on the fly. ''.join()then takes this newly generated list of strings and merges them without any separators.
It’s a clean, one-line solution for formatting mixed data types into a single string.
Creating a custom print function
def print_no_space(*args):
print(*args, sep='', end='')
print_no_space("Hello", 123, "World")
print() # Add a newline--OUTPUT--Hello123World
If you often need to print without spaces, creating a custom function keeps your code clean and reusable. The print_no_space function is a simple wrapper that modifies the behavior of the built-in print().
- The
*argssyntax allows the function to accept any number of arguments, making it flexible. - Inside, it calls the standard
print()function, but overrides the defaults by settingsep=''andend=''.
This gives you a convenient shortcut for printing multiple items consecutively on a single line without any extra characters.
Using sys.stdout for direct output
import sys
for char in "Python Programming":
if char != ' ':
sys.stdout.write(char)
sys.stdout.write('\n') # Add a newline--OUTPUT--PythonProgramming
For maximum control, you can write directly to the standard output stream with sys.stdout.write(). This method is more fundamental than print() and adds no extra characters—not even a newline. You get precise, raw output.
- The code loops through each character, using an
ifstatement to skip spaces andsys.stdout.write(char)to print everything else. - Since
write()doesn't automatically add a newline, one is explicitly added at the end withsys.stdout.write('\n')for clean formatting.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
The string formatting techniques from this article, like using sep='' or join(), are building blocks for real tools. Replit Agent can turn these concepts into production-ready applications:
- Build a utility that generates unique, space-free product keys or coupon codes.
- Create a simple command-line tool that renders ASCII art by printing characters sequentially.
- Deploy a data formatter that converts lists of values into a compact, single-line string for logs or APIs.
Bring your own app ideas to life. Describe what you want to build, and Replit Agent will write the code, handle testing, and deploy it for you, right in your browser.
Common errors and challenges
Even with the right techniques, you might encounter issues like type errors or unwanted newlines; here’s how to solve them.
A common hurdle is the TypeError, which often appears when you try to combine strings with other data types, like numbers.
- Using the
+operator to add an integer to a string will fail. - The
''.join()method also requires an iterable of strings, so passing it a list containing numbers will cause an error.
The fix is to explicitly convert all non-string items using str() before you attempt to join or concatenate them.
If your output unexpectedly appears on multiple lines, you've likely forgotten to override the default behavior of the print() function. Each call to print() automatically adds a newline character unless you specify otherwise. To keep your output on a single line when printing in a loop, simply add the end='' parameter to every print() call.
When building a long string from many smaller pieces, your choice of method impacts memory usage and performance.
- Using the
+=operator in a loop is often inefficient. Each time you use it, Python creates an entirely new string in memory, which can slow your program down with large datasets. - The
''.join()method is much more efficient. It calculates the total required space once and then constructs the final string in a single operation.
For performance-critical applications, it's best to favor ''.join() over repeated concatenation with +=.
Troubleshooting TypeError when mixing data types
A TypeError is a common roadblock when you try to combine different data types, like a string and a number, using the + operator. Python doesn't automatically convert the number to a string, which causes the operation to fail.
This error is easy to miss but simple to fix. For example, the following code attempts to concatenate a string with an integer, which will raise a TypeError.
user_id = 12345
print("User" + user_id + "logged in")
The + operator can't decide whether to perform addition or string concatenation when it encounters both a string and an integer. The corrected code below shows how to resolve this ambiguity.
user_id = 12345
print("User" + str(user_id) + "logged in")
# Alternatively:
print(f"User{user_id}logged in")
To fix the TypeError, you must explicitly convert non-string types before combining them. The + operator can't join a string and an integer, so wrapping the number in str(), like str(user_id), resolves the ambiguity by telling Python to treat it as text.
An even cleaner approach is using an f-string, such as f"User{user_id}logged in". F-strings automatically handle this type conversion, making your code more readable. Watch for this error whenever you build strings from variables of different types.
Fixing unexpected newlines with end=''
Sometimes, even when you use end='', your output still breaks into new lines. This usually happens when the strings you're printing already contain newline characters, like \n. The code below shows how this can catch you by surprise.
for line in ["Line1\n", "Line2\n", "Line3\n"]:
print(line, end='')
Even though end='' is used, each string in the list contains its own newline character (\n), forcing each item onto a new line. The corrected code below shows how to fix this behavior for the intended output.
for line in ["Line1\n", "Line2\n", "Line3\n"]:
print(line.strip(), end='')
The end='' parameter can't remove newlines that are already part of your string. If you see unexpected line breaks, your data likely contains hidden \n characters, which is common when reading from files or APIs.
- The solution is to use the
.strip()method on your string before printing it. - This removes leading and trailing whitespace, including newlines, allowing
end=''to work as intended.
Optimizing memory usage with join() vs +=
When building a large string, the method you choose matters. While the += operator seems straightforward, it's often less efficient than join() because it creates a new string in memory with every loop. The code below demonstrates this performance bottleneck.
large_list = [str(i) for i in range(10000)]
result = ""
for item in large_list:
result += item
print(result[:10])
The += operator repeatedly creates and discards strings, causing significant memory overhead and slower performance with large lists. The corrected code below demonstrates a much more memory-efficient approach for building the final string.
large_list = [str(i) for i in range(10000)]
result = ''.join(large_list)
print(result[:10])
The += operator is inefficient for building large strings. With each loop, it creates an entirely new string, which consumes memory and slows your code. In contrast, the join() method is far more performant. It calculates the total required space just once, then assembles the final string in a single operation. You should always favor join() when combining many strings, especially when performance matters or you're working with large datasets.
Real-world applications
These formatting techniques are the building blocks for practical applications, from dynamically constructing URLs to generating custom ASCII art.
Building URLs by concatenating components with join()
You can reliably build URLs by using the join() method to combine components like a base address and API endpoints with a forward slash as the separator.
base_url = "https://example.com"
endpoint = "api"
resource = "users"
user_id = "12345"
url = '/'.join([base_url, endpoint, resource, user_id])
print(url)
This code assembles a URL from a list of its parts. The join() method is a smart choice here because it prevents common formatting errors. If you used the + operator instead, you might accidentally create URLs with missing or double slashes.
- The method is called on the separator string, in this case
'/'. - It then inserts that separator between each item from the list.
This approach guarantees a correctly structured URL every time, making your code cleaner and more reliable.
Creating ASCII art banners using string repetition
By repeating characters with the * operator, you can easily generate decorative banners for your command-line applications.
def create_banner(text, width=40):
border = '+' + '-' * (width - 2) + '+'
content = '|' + text.center(width - 2) + '|'
return f"{border}\n{content}\n{border}"
print(create_banner("Welcome to Python"))
This function, create_banner, dynamically generates a framed text box. It builds the banner by combining several string formatting methods.
- The
text.center()method is key, positioning your message precisely within the specified width by padding it with spaces for alignment. - An f-string then assembles the final output, joining the top border, the centered content, and the bottom border into a single multi-line string using newline characters (
\n).
This returns a neatly formatted banner ready for printing.
Get started with Replit
Put these techniques into practice and build a real tool. Tell Replit Agent to “build a utility that generates a space-free product key from a list of numbers” or “create a simple ASCII art generator.”
Replit Agent writes the code, tests for errors, and deploys your app right from your browser. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

.png)
.png)
.png)