Reputation: 9
print('{0:^10}'.format('hi')) output - hi
'{0:^10}'.format('hi') output -' hi '
Can I output the first sentence like the second one by using the print
function?
Upvotes: 0
Views: 50
Reputation: 12620
You can use repr
which for strings returns a representation of the literal you would use to create the string:
>>> print(repr('{0:^10}'.format('hi')))
' hi '
There are other ways to do it, with or without backslash:
>>> print('\'{0:^10}\''.format('hi'))
' hi '
>>> print("'{0:^10}'".format('hi'))
' hi '
But I think for using repr
is the clearest and more general way.
Upvotes: 0
Reputation: 1237
yes, you just need to escape your single '
s by putting a backslash \
before them - this is called string escaping and helps your print
function to notice, that these characters should be displayed as plain text and not be interpreted like usual, "special" characters.
Upvotes: 1