tags: python string fstring Python fstrings allow you to format strings by interpolating expressions. ```python x = 257 y = 1.554 f"{x} {x:05d} {x:08x} {x:o}" f"{y:e} {y:.2f} {0.5:.2%}" z = 24242224224 f"{z:,.2f}" # Alignment f"{1:<8d} {1:<8d} {1:<8d}" #vs f"{1:>8d} {1:>8d} {1:>8d}" ``` ## Padding You can specify left, centre or right alignment using `<`, `>` or `^`, and the padding symbol before this. You can use a variable as the padding symbol provided it is a single-character string. ```python >>> a = 1 >>> b = 3.14 >>> c = "hello" >>> width = 30 >>> f"{c:#^{width}}" '############hello#############' >>> f"{c:_<{width}}" 'hello_________________________' >>> f"{c:*>{width}}" '*************************hello' >>> d="_*_" >>> f"{c:{d}>{width}}" Traceback (most recent call last): File "", line 1, in ValueError: Invalid format specifier >>> d="*" >>> f"{c:{d}>{width}}" '*************************hello' >>> f"{45:#>17.3f}" '###########45.000' ``` # fstring formatters You define a `__format__(self,fmtstring)` method in a class, and that is called by an fstring, with whatever follows the `:` being passed as the argument `fmtstring`. Silly example: ```py import sys class A: n = 0 @classmethod def inc(cls): cls.n += 1 return cls.n def __format__(self,fmt): print(f"format: {fmt}",file=sys.stderr) return str(self.inc()) a = A() print(f"{a:flibble} {a:hexvision}") print(f"{a:flibble} {a:hexvision}") print(f"{a:flibble} {a:hexvision}") print(f"{a:flibble} {a:hexvision}") ```