How to print newline in Python without an automatic indent in the next line?

181 views Asked by At

I was incorporating the \n command into my code to print the next part onto the next time. While the original goal was achieved, there was an unexpected indent only for the first line of the result that started on the newline.

print("Rank:\n", rank_desc)

That results in:

Rank:
 count   500.000000
mean   250.500000
std    144.4181833
min      1.000000
etc...

One way to solve the issue is to just have two print statements. However, now matter how I sliced and mixed the \n in my code, I could not get the indent to go away.

4

There are 4 answers

0
Bibhav On BEST ANSWER

use sep parameter of print for this:

# sep stands for separator
print("Rank:", rank_desc, sep='\n')
2
Sash Sinha On

Using a comma in the print function separates the items with a space by default because that is the default value for the sep parameter (print(*objects, sep=' ', ...)).

Try setting it to something else:

print("Rank:\n", rank_desc, sep='')

Or handing concatenation yourself using a plus:

print("Rank:\n" + rank_desc)

Or via an f-string:

print(f"Rank:\n{rank_desc}")

Output for all of the above:

Rank:
count   500.000000
mean   250.500000
std    144.4181833
min      1.000000
etc...
0
sant chanana On

You can format the output using string concatenation:

print("Rank:" + rank_desc)

This approach ensures there's no additional indentation in the output.

0
Roko On

In python using "," adds an extra formating space for example:

print("a","b")

wouldn't print "ab" but "a b" so your code first prints "Rank:" then a newline and then prints a space because of the ",".

use:

print("Rank/n" + rank_desc)

to mitigate this issue if rank_desc is a string or:

print(f"Rank:\n{rank_desc}")

if it isn't. The f before the string indicates that it's an f-string. The expression within curly braces {rank_desc} is evaluated, and its value is inserted into the string.