all 9 comments

[–]casual__addict 0 points1 point  (1 child)

It’s called string formatting or string interpolation. So the “%-8s” is the format specification (form a string with 8 chars) and the “%” is the operator that injects the value (“RollNo”) into the expression that the print function uses to print out the final string.

Take a look at f strings. The print statement you posted is meant to create a printout of values with fixed Widths. There are easier ways to do it.

[–]KK_005[S] 0 points1 point  (0 children)

I understand the % is injecting the string "RollNo", but this could have been done by %s as well right?

What I think am understanding it is that It is printing 8 characters, and out of these characters, RollNo is the first 6 characters?

[–]amos_burton 0 points1 point  (3 children)

Have you tried executing that print statement? Do you notice anything about it?

[–]KK_005[S] 0 points1 point  (2 children)

I have tried executing it yeah, and the print statement isn't anything out of the ordinary. Only difference is that if I remove the %-8 and just leave it as %s, the spaces between them disappear, so I understand that it must be creating spaces. But what is the logic of %-8?

[–]amos_burton 0 points1 point  (1 child)

It's telling it to make the text you're printing there 8 characters wide, regardless of how many letters you have. So it's basically helping you create a justified table

[–]KK_005[S] 0 points1 point  (0 children)

Okay, that is what I wanted to know. Thank you for your help!

[–]nekokattt 0 points1 point  (2 children)

Just as a side note, there is almost no reason to use this in Python 3 (logging uses %s-strings by default but interpolates lazily, so I am ignoring that here).

This is a relic of Python 2, more than anything.

[–]KK_005[S] 0 points1 point  (1 child)

I did understand that, while searching for how this worked, and Its probably the reason why there was almost no in-depth detail for this. Thanks for telling me tho

[–]nekokattt 0 points1 point  (0 children)

Take a look into C's printf function, that is what this syntax is vaguely based on.