954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Quiz of the day: print format

What does this print statement produce and why? Learned it today, I still must be a newbie.

print('%0*d' % (3, 7))
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Ok, since  nobody  has  replied  yet, I  thought  I'd  give  it a shot.
Warning -> I'm not an expert, at all. I just started learning python.

The above  statement   prints 7, left zero  padded,  so that  the total
number of digits is 3. You can also put 3 in the format string instead:

print('%03d' % 7)
m4ster_r0shi
Posting Whiz in Training
230 posts since Mar 2010
Reputation Points: 154
Solved Threads: 31
 

Is "d" here stands for "digit"?
this bellow code does the same but instead of 0's it prints empty spaces"

print('%0*s' % (3, 7))


what about "s" here? does it mean "string"?

M.S.
Junior Poster in Training
56 posts since Jul 2011
Reputation Points: 28
Solved Threads: 7
 

Is "d" here stands for "digit"? this bellow code does the same but instead of 0's it prints empty spaces"

print('%0*s' % (3, 7))

what about "s" here? does it mean "string"?


Yes, 's' means string. In principle, the str() method is applied to the argument. Better learn to use the new format() operator which is more powerful than %. For example

>>> print( "{0:{1}^{2}s}".format(" 77 ", "=", 60) )
============================ 77 ============================

Some more examples here http://www.daniweb.com/software-development/python/code/232375

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

It is more like 'use the objects __str__ method ie use str function to object'

How about these, then:

print('%*r' % (6, '7'))
 print('%*r' % (6, 7))


Yes, format is good to learn also, but there is lot of code with 'modulo formatting', so you better learn both.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Yes, 's' means string. In principle, the str() method is applied to the argument. Better learn to use the new format() operator which is more powerful than %. For example

>>> print( "{0:{1}^{2}s}".format(" 77 ", "=", 60) )
============================ 77 ============================

Some more examples here http://www.daniweb.com/software-development/python/code/232375


Shows that the language of format is powerfull, but I would still prefer for readability:

print(' 77 '.center(60, '='))

or

print( "{info:{char}^{width}s}".format(info=" 77 ", char="=", width=60))
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

What this new format function does and how it works?

def print_formats(num):
    print('{num:016b} {num:04x} {num:06o} {num:05d}'.format(**locals()))

print_formats(1234)
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

It is more like 'use the objects __str__ method ie use str function to object'

How about these, then:

print('%*r' % (6, '7'))
 print('%*r' % (6, 7))

Yes, format is good to learn also, but there is lot of code with 'modulo formatting', so you better learn both.

>> print('%*r' % (6, '7'))
   '7'
>>> print('%*r' % (6, 7))
     7

So for repr the quotes count for width, so string 7 start two spaces before than number 7 to finish at same position.

And how about this then, what it does?

print('%u' % -7)
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

I think It only accepts Integers and convert them to Unicode strings:

>>> a='%u' % -7
>>> print type(a)
<type 'str'>
M.S.
Junior Poster in Training
56 posts since Jul 2011
Reputation Points: 28
Solved Threads: 7
 

I think It only accepts Integers and convert them to Unicode strings:

>>> a='%u' % -7
>>> print type(a)
<type 'str'>


Nope it is not, and it is not (anymore) unsigned integer like in C, but it is synonym for %i and %d. Better to avoid using it, as it will be deprecated and is only confusing. This is only to show "Python is not C".

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Python27 and higher ...

# pad with leading zeroes
print( "value is {v:0{digits}n}".format(v=2, digits=3) )

"""result -->
value is 002
"""
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

I know this thread is more than 2 weeks old, but I have a question about the format() syntax .

print( "{0:{1}^{2}s}".format(" 77 ", "=", 60) )


When specifying the field_name, you don't need to place {} around the '0'. I understand that it refers to the 0th element of the list. However, the fill character field is specified here by {1}, and the width field is specified by {2}. These obviously also refer to the list passed in format(), but they include {}.

I can't find anything in the documentation to indicate why this is. Could someone explain why this syntax is used?

Purkinje
Newbie Poster
19 posts since Jan 2011
Reputation Points: 10
Solved Threads: 1
 

Those two are nested inside a format specifier not information to print.

>>> print( ":{0}^{1}s".format("=", 60) )
:=^60s
>>> print( "{0:=^60s}".format(" 77 ") )
============================ 77 ============================
>>>
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 
Those two are nested inside a format specifier not information to print.

That wasn't my question. I was simply questioning the syntax of the format specifier, which I could not find in the documentation. Outside of the format specifier, Python, in general, uses '{' and '}' to refer to dictionary declarations. However, within the format specifier, it refers to elements within the tuple passed into the format() method. Why use {} within theformat_spec, but not the field_name?

Please see http://docs.python.org/library/string.html#format-string-syntax for the meaning of the bolded terms I used.

Purkinje
Newbie Poster
19 posts since Jan 2011
Reputation Points: 10
Solved Threads: 1
 

It is dictionary in general sense, but you can access unspecified keys by numeric key:

>>> family
{'father': 'Tony', 'mother': 'Edlira'}
>>> print("Father is {father} and mother is {mother}".format(**family))
Father is Tony and mother is Edlira
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Ah, thanks for the clarification on that. I appreciate your help! It's interesting to see what you can do with strings.

Purkinje
Newbie Poster
19 posts since Jan 2011
Reputation Points: 10
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: