From b001e830bce698097109ad2a9af0dacf1ef9f0cf Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Sun, 22 Mar 2009 18:56:23 -0400 Subject: [PATCH] more on format specifiers --- strings.html | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/strings.html b/strings.html index 796b4b2..7130a58 100644 --- a/strings.html +++ b/strings.html @@ -153,8 +153,45 @@ def approximate_size(size, a_kilobyte_is_1024_bytes=True):
 >>> import humansize
->>> 
+>>> si_suffixes = humansize.SUFFIXES[1000]      
+>>> si_suffixes
+['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
+>>> "1000{0[0]} = 1{0[1]}".format(si_suffixes)  
+'1000KB = 1MB'
 
+
    +
  1. Rather than calling any function in the humansize module, you'll just grab one of the data structures it defines: the list of "SI" (powers-of-1000) suffixes. +
  2. This looks complicated, but it's not. {0} would refer to the first argument passed to the format() method, si_suffixes. But si_suffixes is a list. So {0[0]} refers to the first item of the list which is the first argument passed to the format() method: 'KB'. Meanwhile, {1[0]} refers to the second item of the same list: 'MB'. Everything outside the curly braces — including 1000, the equals sign, and the spaces — is untouched. The final result is the string '1000KB = 1MB'. +
+ +

What this example shows is that format specifers can access items and properties of data structures using (almost) Python syntax. The following things "just work": + +

+ +

Just to blow your mind, here's an example that combines all of the above: + +

+>>> import humansize
+>>> import sys
+>>> "1MB = 1000{0.modules[humansize].SUFFIXES[1000][0]}".format(sys)
+'1MB = 1000KB'
+ +

Here's how it works: + +

Note that (k, v) is a tuple. I told you they were good for something.