1

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.

Max
  • 21
  • 3
  • use `print("rank', rank_disk, sep='\n')` . it will print value in new line every time without space – vegan_meat Aug 09 '23 at 11:17
  • Apologies if unclear as this is my first question. The variable rank_desc comes from using the Series.describe() method on a list of Fortune500 companies and their ranking. As I said, if I simply use 2 print statements, which is the same as just printing the rank_desc variable, there are no indents. – Max Aug 09 '23 at 11:20
  • Does this answer your question? [Print without space in python 3](https://stackoverflow.com/questions/12700558/print-without-space-in-python-3) also: [How to remove the space while printing with newline \n?](https://stackoverflow.com/questions/68118436/how-to-remove-the-space-while-printing-with-newline-n) – Abdul Aziz Barkat Aug 09 '23 at 11:23

4 Answers4

4

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...
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
2

You can format the output using string concatenation:

print("Rank:" + rank_desc)

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

1

use sep parameter of print for this:

# sep stands for separator
print("Rank:", rank_desc, sep='\n')
Bibhav
  • 1,579
  • 1
  • 5
  • 18
0

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.

Roko
  • 1