Rohit Sasikumar
Rohit Sasikumar

Reputation: 89

Formatting a line with spaces at the beginning

Consider below piece of code

line = "I am writing a question"
print('{0: >10}'.format(line))

This does not work as expected. I expected output to be

'          I am writing a question'

I know I can achieve this by other means like printing the spaces first using one print statement and then print the sentence. But curious to know what I might be doing wrong.

Upvotes: 0

Views: 401

Answers (2)

gosom
gosom

Reputation: 1319

There is a built in method :

https://docs.python.org/2/library/stdtypes.html#str.rjust

v = 'hi'
print v.rjust(4, ' ');

prints

 '  hi'

Upvotes: -1

Martijn Pieters
Martijn Pieters

Reputation: 1122022

Your line is longer than 10 characters; the width is a minimal value and applies to the whole column. If you wanted to add 10 spaces, always, prefix these before the format:

print('          {0}'.format(line))

If you always wanted to right-align the string in a column of 33 characters (10 spaces and 23 characters for your current line), then set the column width to that instead:

print('{0:>33}'.format(line))

Now, when your line value is longer or shorter, the amount of whitespace will be adjusted to make the output 33 characters wide again.

Demo:

>>> line = "I am writing a question"
>>> print('          {0}'.format(line))
          I am writing a question
>>> print('{0:>33}'.format(line))
          I am writing a question
>>> line = "question"
>>> print('{0:>33}'.format(line))
                         question

Upvotes: 4

Related Questions