Fabio Capezzuoli
Fabio Capezzuoli

Reputation: 619

Python output: how to remove indent of a new line?

There's an annoying little problem with Python print() output: the first line after \n is indented. Like this:

num = 888
print("The lucky number is:\n", num)

The lucky number is:
 888

I'd really like to have '888' aligned left. How can I do it?

Upvotes: 4

Views: 10712

Answers (2)

Inon Peled
Inon Peled

Reputation: 711

print('The lucky number is:', num, sep='\n')

Output:

The lucky number is
888

Upvotes: 4

TerryA
TerryA

Reputation: 59974

You can use string formatting to put num wherever you want in the string:

print(f"The lucky number is:\n{num}")

If f-strings aren't available to use, you can also use str.format():

print("The lucky number is:\n{}".format(num))

And finally, while I don't recommend it because it's deprecated, you can use percentage symbol formatting:

print("The lucky number is:\n%d" % num)

Upvotes: 6

Related Questions