Depending on your requirements, following are some ways in Python in which you can print to the same line:
Print to Same Line Using print()
Using Python's print()
method, you can print to the same line by setting the end
parameter to an empty string, for example, like so:
print('...', end='') # ...
To demonstrate the effect, you can see the result of the following code:
for x in range(5): print(x, end='') # 01234
Print to Same Line Without Using print()
As an alternative, for strings, you can also use the sys
module to achieve the same, for example, in the following way:
import sys for x in range(5): sys.stdout.write(str(x)) # 01234
It's important to note that sys.stdout.write()
only accepts strings, which is why in the example above, the integers need to be converted to strings. If you don't do that, you will get a TypeError
.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.