"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Eliminate Spaces in Python Print Statements?

How to Eliminate Spaces in Python Print Statements?

Published on 2024-11-08
Browse:779

How to Eliminate Spaces in Python Print Statements?

Removing Spaces in Python Print Statements

In Python, printing multiple items often results in unintended spaces. This can be addressed using the sep parameter to eliminate these spaces. For instance, consider this:

print("a", "b", "c")

This output will include spaces:

a b c

To eliminate them:

print("a", "b", "c", sep="")

This will produce:

abc

In addition to the sep parameter, Python offers several options for controlling print output. When attempting to concatenate a string with a non-string value, such as an integer, it's essential to first convert the value to a string.

To print values without spaces, including strings and non-strings, consider the following:

print("a = ", a, ", b = ", b, sep="")  # Python 2.x and 3.x
print("a = "   str(a)   ", b = "   str(b))  # Python 2.x and 3.x
print("a = {}, b = {}".format(a, b))  # Python 3.6 
print(f"a = {a}, b = {b}")  # Python 3.6 

For situations where using f-strings (the latest option) might not be feasible (e.g., Python versions before 3.6), the following trick can be employed:

print("a = {a}, b = {b}".format(**locals()))
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3