How do I align text output in Python?

str.format already has the possibility to specify alignment. You can do that using {0:>5}; this would align parameter 0 to the right for 5 characters. We can then dynamically build a format string using the maximum number of digits necessary to display all numbers equally: >>> lower = [70, 79, 88, 97, 106, 115] >>> … Read more

Star * operator on left vs right side of an assignment statement

The difference between these two cases are explained when also taking into consideration the initial PEP for extended unpacking: PEP 3132 — Extended iterable unpacking. In the Abstract for that PEP we can see that: This PEP proposes a change to iterable unpacking syntax, allowing to specify a “catch-all” name which will be assigned a … Read more

Multiprocessing Share Unserializable Objects Between Processes

Most of the time it’s not really desirable to pass the reference of an existing object to another process. Instead you create your class you want to share between processes: class MySharedClass: # stuff… Then you make a proxy manager like this: import multiprocessing.managers as m class MyManager(m.BaseManager): pass # Pass is really enough. Nothing … Read more

Printing subscript in python

If all you care about are digits, you can use the str.maketrans() and str.translate() methods: example_string = “A0B1C2D3E4F5G6H7I8J9” SUB = str.maketrans(“0123456789”, “₀₁₂₃₄₅₆₇₈₉”) SUP = str.maketrans(“0123456789”, “⁰¹²³⁴⁵⁶⁷⁸⁹”) print(example_string.translate(SUP)) print(example_string.translate(SUB)) Which will output: A⁰B¹C²D³E⁴F⁵G⁶H⁷I⁸J⁹ A₀B₁C₂D₃E₄F₅G₆H₇I₈J₉ Note that this won’t work in Python 2 – see Python 2 maketrans() function doesn’t work with Unicode for an explanation of … Read more

TypedDict when keys have invalid names

According to PEP 589 you can use alternative syntax to create a TypedDict as follows: Movie = TypedDict(‘Movie’, {‘name’: str, ‘year’: int}) So, in your case, you could write: from typing import TypedDict RandomAlphabet = TypedDict(‘RandomAlphabet’, {‘A(2)’: str}) or for the second example: RandomAlphabet = TypedDict(‘RandomAlphabet’, {‘return’: str}) PEP 589 warns, though: This syntax doesn’t … Read more