DongHyeok Kim
DongHyeok Kim

Reputation: 9

how can I output ' ' with using print in python

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

Answers (4)

mad_
mad_

Reputation: 8273

Or Just enclose in double quotes

print("'{0:^10}'".format("hi")) 

Upvotes: 1

Stop harming Monica
Stop harming Monica

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

dashiell
dashiell

Reputation: 812

No need for repr

>>> print('\'{0:^10}\''.format('hi'))
'    hi    '

Upvotes: 0

Cut7er
Cut7er

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

Related Questions