How Do I Print An Integer With A Set Number Of Spaces Before It?
Solution 1:
This print("{0:10d}".format(5))
will print 5 after 9 blanks.
For more reference on formatting in python refer this.
Solution 2:
In general case, we could use string .format()
:
>>> '{:<30}'.format('left aligned')
'left aligned '>>> '{:>30}'.format('right aligned')
' right aligned'>>> '{:^30}'.format('centered')
' centered '>>> '{:*^30}'.format('centered') # use '*' as a fill char'***********centered***********'
We could also do that with f strings for python >3.6
>>> f"{'left aligned':<30}"'left aligned '>>> f"{'right aligned':>30}"' right aligned'>>> f"{'centered':^30}"' centered '>>> f"{'centered':*^30}"# use '*' as a fill char'***********centered***********'
Solution 3:
I would do something like this:
>>>print(10*' ',10)
10
>>>print(5*' ',5)
5
>>>x=5>>>print(x*' ',x)
5
>>>
Solution 4:
You could try this
x = " "
y = 10
print((x*5), y)
And your output will be
10
You assign x to a string with a space, then when printing, you simply multiply the string with space by the number of spaces you want before y.
Solution 5:
Using ljust or rjust:
These python methods take a string and pad
it either on the left or right to make it a set number of chars
for printing to the console as you want.
To give an example with .rjust
:
num = 1234
chars = 9
print(str(num).rjust(chars))
this will output:
" 1234"
or using .ljust
would give you:
"1234 "
One thing to note is that .ljust
and .rjust
are significantly different to printing a set number of spaces ' '
before or after the int
as they allow you to specify the total length of the string rather than the whitespace before it. This is a key thing to consider for example when printing a table as with these methods, the columns can be made to be set widths making it neat. Whereas simply adding spaces beforehand will result in varying widths as the number of digits
of the integers
will change causing the total string length to change making the widths vary.
Of course, if you wanted to, you could still specify the total string length and then calculate how many spaces need placing before or after the int
.
So .rjust
may be something like:
num = 1234
chars = 9print(' ' * (chars - len(str(num))) + str(num))
noticing that here, I have concatenated the num
as a string onto the whitespace with +
rather than using a comma in the print statement as the comma will place an added space between the two.
and .ljust
would be the same but the num
printed first:
print(str(num) + ' ' * (chars - len(str(num))))
however, all this work is unnecessary and looks very messy considering you can just use the original two built-in python methods :)
Post a Comment for "How Do I Print An Integer With A Set Number Of Spaces Before It?"