http://www.tiddlywiki.com/
<<list all>>
<<list missing>>
<<allTags>>
<<list orphans>>
<<timeline>>
<<search>><<closeAll>><<permaview>><<saveChanges>><<slider chkSliderOptionsPanel OptionsPanel options "Change TiddlyWiki advanced options">>
//This rearranges the sidebars\nvar contentWrapper = document.getElementById('contentWrapper');\nvar sidebar = document.getElementById('sidebar');\nsidebar.insertBefore(document.getElementById('mainMenu'),document.getElementById('sidebarOptions'))\n
[[Python]] [[Grimoire|Introduction]]
You wish to convert a number to the corresponding string representation. For example, you want to convert a number like 144 to the string {{{'144'}}}. \n \nThe simplest way is to use the built-in function {{{str()}}}, or the backquote notation {{{`144`}}}. Both solutions will convert the number to a string in the most straightforward way. \n \n{{{\nV = 187.5\nS = str(V) # Produces '187.5'\n}}}\n \nIf {{{V}}} contains an integer or long integer, and you want to convert the number to hexadecimal or octal representation, use the built-in functions {{{hex()}}} or {{{oct()}}}. \n \n{{{\n>>> hex(187)\n'0xbb'\n>>> oct(187)\n'0273'\n}}}\n \nIf fancier formatting is required, such as rounding a floating-point number to a given number of decimal places, or padding a number with zeros, use the % operator on strings, which allows more precise control of the output. \n \n{{{\n>>> "%04d" % (87,)\n'0087'\n>>> "%.2f" % (187.375,)\n'187.38'\n}}}\n \n(See the Library Reference manual for the complete details of the available format characters.) \n \nThere's no library function to convert a number to its base-2 representation, so here's a function to do the job. \n \n{{{\ndef atob(number):\n """Returns a string containing the binary representation of a number"""\n if number < 0:\n prefix = "-" ; number = -number\n elif number == 0: return "0"\n else:\n prefix = ""\n\n # Loop, looking at the lowest bit of the number an\n s = ""\n while number > 0:\n s = chr( 48+ (number 1) ) + s\n number = number >> 1\n return prefix + s\n}}}\n
You have a tuple, and want to turn it into a list. Or, the opposite problem: a list that you want to turn into a tuple. \n \nThe built-in functions {{{tuple()}}} and {{{list()}}} convert any sequence type into a tuple or list containing the same items in the same order. \n \n{{{\n>>> tuple( [1,2,3] )\n(1, 2, 3)\n>>> list ( ('monty', "python's", "fliegende", "circus") )\n['monty', "python's", 'fliegende', 'circus']\n>>> tuple('Dr Gumby!')\n('D', 'r', ' ', 'G', 'u', 'm', 'b', 'y', '!')\n}}}\n \n''Discussion:'' \n \n{{{list()}}} was introduced in Python 1.5; in previous versions, the following idiom was used to convert things to lists: \n \n{{{\nlist = map(None, (1,2,3,4) )\n}}}\n \nHere's how the above line of code works: the {{{map()}}} built-in function is used to evaluate a function for every value in a sequence type like a tuple, and returns a list containing the function's output for each value in the input sequence. Put another way, {{{map(F, seq)}}} returns a new list containing {{{[F( seq[0] ), F( seq[1] ), ... ]}}}. If {{{None}}} is passed as the function {{{F}}}, then {{{map()}}} simply returns the elements of the sequence {{{[seq[0], seq[1], ...]}}}. \n \nYou may still see the above use of {{{map()}}} in programs that attempt to be compatible with older versions of Python; if you don't care about backward compatibility, simply use {{{list()}}} which is clearer. \n
After creating a dictionary, you want to loop over the dictionary's contents and do something for each entry, such as printing them. \n \nThe {{{keys()}}} method of dictionaries returns a list of the dictionary's keys, arranged in essentially random order: \n \n{{{\n>>> for colr in fr_colours.keys(): print colr\n...\nyellow\nred\nblack\nwhite\nblue\n}}}\n \nIf you want to loop over the contents in some sorted order, you'll have to retrieve the list of keys and sort it before looping through it. \n \n{{{\n>>> keylist = fr_colours.keys() ; keylist.sort()\n>>> for colr in keylist: print colr\n...\nblack\nblue\nred\nwhite\nyellow\n}}}\n \nRemember that the {{{sort()}}} list method sorts a list in-place and returns {{{None}}}. {{{for colr in fr_colours.keys().sort()}}}will not work, because the value of {{{fr_colours.keys().sort()}}} is {{{None}}}. \n \n''Discussion:'' \n \nThe list returned by {{{keys()}}} is arranged randomly, because the key/value pairs are scattered across random bins in a hash table. Dictionaries therefore don't impose any ordering on their contents. For example, if you assemble a dictionary element-by-element, and print the dictionary after each new key/value pair is added, there's no order to how the contents are displayed. \n \n{{{\n>>> d = {} ; d['red'] = 'rouge' ; print d\n{'red': 'rouge'}\n>>> d['blue'] = 'bleu' ; print d\n{'red': 'rouge', 'blue': 'bleu'}\n>>> d['yellow'] = 'jaune' ; print d\n{'yellow': 'jaune', 'red': 'rouge', 'blue': 'bleu'}\n>>> d['green'] = 'vert' ; print d\n{'yellow': 'jaune', 'red': 'rouge', 'green': 'vert', 'blue': 'bleu'}\n}}}\n \nThere are two other methods available for retrieving the contents of a dictionary. If your loop will require each key and its corresponding value, you can use the {{{items()}}} method, which returns a list of {{{(key, value)}}} 2-tuples. Again, the list contents are arranged in a random order. \n \n{{{\n>>> for english, french in fr_colours.items():\n... print english, '\st', french\n...\nyellow jaune\nred rouge\nblack noir\nwhite blanc\nblue bleu\n}}}\n \nLeast commonly used of all, the {{{values()}}} method returns a list containing only the values from a dictionary. \n \n{{{\n>>> for colr in fr_colours.values(): print colr\n...\njaune\nrouge\nnoir\nblanc\nbleu\n}}}\n \nThe way to keep these method names straight is to remember that dictionaries map from keys to values; the {{{keys()}}} and {{{values()}}} methods return a list of the corresponding elements of the dictionary. That leaves {{{items()}}} to return a list of 2-tuples. \n
If a default value is some expression, that expression is evaluated at the time the {{{def}}} statement is executed, not when the function is called. Consider the following example: \n \n{{{\ndefault_level = 9\ndef new_compressor(compresslevel = default_level):\n print 'Compression level:', compresslevel\n\nnew_compressor() # Prints the default value\ndefault_level = 2 # Will this change the default value?\nnew_compressor()\n}}}\n \nWhen this code is run, it will print: \n \n{{{\nCompression level: 9\nCompression level: 9\n}}}\n \nRemember, {{{def}}} is an executable statement, binding the function's name "{{{new_compressor}}}" to a function object. At that time, {{{default_level}}} has a value of 9, so that's used as the default value of compresslevel. Subsequently changing the value of {{{default_level}}} has no effect on the default value of the function. It's not possible to change the object that's been defined as the default value. However, if an object is mutable and can be modified in place, as a list or dictionary can be, then any modification made to that object will change the default. Another example will make this clearer, I hope: \n \n{{{\ndef modify_list(List = []):\n print 'Before:', id(List), List\n List.append( 1 )\n print 'After: ', id(List), List\n}}}\n \nCalling this function with {{{modify_list()}}} will output: \n \n{{{\nBefore: 135048144 []\nAfter: 135048144 [1]\n}}}\n \nThe first number, the value of {{{id(List)}}}, is an integer guaranteed to be unique for this object while the object exists, and is usually derived from the machine address at which the object resides. The value printed here will vary from run to run of the Python interpreter, but will remain the same in each execution. On the first call of {{{modify_list()}}}, the list object assigned as the default value is changed. A second, identical call will produce: \n \n{{{\nBefore: 135048144 [1]\nAfter: 135048144 [1, 1]\n}}}\n \n{{{id(List)}}} is the same on both function calls, so the same list object is assigned as the default value, but the contents of that object have been changed, which doesn't affect the value returned by {{{id(List)}}}. New users are often surprised by this behaviour, and wonder if it's a bug in Python; it's not, and follows consistently from Python treating everything as a reference. \n
Some programming languages, such as the scripting language in MATLAB, allow calling a function and ignoring some of its return values. You need to do this in Python, ignoring some value returned from a function. \n \nIf the function returns a tuple, as done by most functions that return multiple results, treat the return value as a tuple and slice it to obtain the results that you need. \n \n{{{\ndef get_rgb_colour(colour_name):\n # ... set R, G, B, to the values\n return R, G, B\n\n# Get just the red component of a colour\ntup = get_rgb_colour('teal')\nR = tup[0]\n}}}\n \nThis can be expressed more compactly, though less clearly, without a tuple variable as: \n \n{{{\nR = get_