简体   繁体   中英

string formatting

I am not getting why the colon shifted left in the second time

>>> print '%5s' %':'
    :
>>> print '%5s' %':' '%2s' %':'
 : :

Help me out of this please

In Python, juxtaposed strings are concatenated:

>>> t = 'a' 'bcd'
>>> t
'abcd'

So in your second example, it is equivalent to:

>>> print '%5s' % ':%2s' % ':'

which by the precedence rules for Python's % operator, is:

>>> print ('%5s' % ':%2s') % ':'

or

>>> print ' :%2s' % ':'
 : :

What are you trying to do?

>>> print '%5s' % ':'
    :
>>> print '%5s%2s' % (':', ':')
    : :

You could achieve what you want by mixing them both into a single string formatting expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM