Python print string centered

1.6k Views Asked by At

I would to print centered a string that is more than 1 line

a = "*\n*\n**"

I tried with

print '{0:^20}'.format(a, 'centered')

but it put in the center just the first *, how can i put all the string in center?

1

There are 1 best solutions below

2
On

It actually does center the entire string:

>>> '{0:^20}'.format(a, 'centered')
'       *\n*\n**       '

Note that this puts seven spaces before and after a. I think you are expecting it to center the content of each line, here is how you can do that:

>>> print '\n'.join('{0:^20}'.format(x, 'centered') for x in a.split('\n'))
         *
         *
         **