Archive
sprintf in Python 2
sprintf in Python
str = "pi is %.2f, name is %s" % (3.1415, "Boba") print str # pi is 3.14, name is Boba
Dictionary-based string formatting
myDict = {'solo': 'Han Solo',
'jabba': 'Jabba the Hutt'}
print "%(solo)s was captured by %(jabba)s." % myDict # Han Solo was captured by Jabba the Hutt.
Values are taken from the dictionary myDict. In the pattern you need to specify the keys in parentheses.
What is it good for? It’s more readable because otherwise when you see “%s” you have to check on the right side what it is, then you jump back with your eyes, etc. Python programming is serious stuff, not to be confused with a table tennis match! :)
Dictionary-based string formatting with locals
A variation of the previous solution:
solo = 'Han Solo'
jabba = 'Jabba the Hutt'
print locals()
# {'solo': 'Han Solo', '__builtins__': <module '__builtin__' (built-in)>, '__file__': './sprintf.py',
#'__package__': None, 'jabba': 'Jabba the Hutt', '__name__': '__main__', '__doc__': None}
print "%(solo)s was captured by %(jabba)s." % locals() # Han Solo was captured by Jabba the Hutt.
locals returns a copy of the local namespace as a dictionary where the keys are the variable names and the values are their respective values.
It means that in the pattern you can use the name of the variables and they will be replaced by their values.
Print in Python 2
Let’s see some examples how to print to the standard output:
#!/usr/bin/env python
import sys
a = "Alice"
b = "Bob"
print a # "Alice\n", i.e. newline added
print b # "Bob\n"
print a, b # "Alice Bob\n", i.e. space is used as separator
print a + b # "AliceBob\n", i.e. the two strings are concatenated
for i in range(10):
print i, # "0 1 2 3 4 5 6 7 8 9", i.e. no newline, but space is still added
# notice the comma after i
print # "\n"
age = 7.5
print "Alice is " + str(age) + " years old." # must use str() for converting
# the float to string
print "%s is %.1f years old" % (a, age) # like C's printf()
for i in range(10):
sys.stdout.write(str(i)) # "0123456789", now you have full control
print
Using the pprint module, you can “pretty print” any data structure. It’s similar to PHP’s print_r function.
import pprint pp = pprint.PrettyPrinter(indent=4) li = [] # some complicated structure pp.pprint(li)
How to print to the standard error? Easy:
#!/usr/bin/env python
import sys
sys.stderr.write("Reactor meltdown! Leave the building immediately!\n")
Autoflush
Printing to the standard output is buffered. What to do if you want to see the output immediately?
import sys import os # reopen stdout file descriptor with write mode # and 0 as the buffer size (unbuffered) sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) print "unbuffered text"
Credits
Update (20130206)
The solution above switches buffered mode off, but you can’t switch it back on because you lose the original sys.stdout file descriptor. I have a more sophisticated solution, available here (autoflush.py) as part of my jabbapylib library.
Usage #1:
autoflush(True) # text that you want to print in unbuffered mode comes here autoflush(False) # back to normal
Usage #2:
# using a context manager
with AutoFlush():
# unbuffered text comes here
sys.stdout.write(...)
# here you are back to normal
Let’s not forget the simplest and most trivial solution either:
sys.stdout.write(...) sys.stdout.flush() # flush out immediately
Update (20210827)
Here is a Python 3 solution:
# auto-flush
sys.stdout = io.TextIOWrapper(
open(sys.stdout.fileno(), 'wb', 0),
write_through=True
)
Pretty print an integer
Exercise: Take an integer and print it in a pretty way, i.e. use commas as thousands separators. Example: 1977 should be 1,977.
Solution:
#!/usr/bin/env python
def numberToPrettyString(n):
"""Converts a number to a nicely formatted string.
Example: 6874 => '6,874'."""
l = []
for i, c in enumerate(str(n)[::-1]):
if i%3==0 and i!=0:
l += ','
l += c
return "".join(l[::-1])
#
if __name__ == "__main__":
number = 6874
print numberToPrettyString(number) # '6,874'
The idea is simple. Consider the number 1977. Convert it to string ("1977") and reverse it ("7791"). Start processing it from left to right and after every third character add a comma: "7" -> "77" -> "779," (comma added) -> "779,1". Now reverse the string ("1,977"). Done.
Links
- http://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators-in-python-2-x (for some more possible solutions)
Update (20131125)
There is an easier way. You can do it with string formatting too:
>>> n = 1977
>>> "{:,}".format(n)
'1,977'
Thanks to Krisztián B. for the tip.
