I'm trying to right align some text, with a variable alignment.
For instance this works:
>>> print '{:>10}'.format('foo')
foo
But this does not:
>>> x = 10
>>> print '{:>x}'.format('foo')
You can align values within a specified length of text by using the < , > , or ^ symbols to specify left align, right align, or centering, respectively. Then you follow the those symbols with a character width you desire. You can also specify the ordinal positions rather than keywords.
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".
Variable name formats are simply naming conventions that are used to compose a variable name. Variable name cannot begin with digits but can comprise of it. Variable names cannot be keywords. Variable names currently doesn't support symbols except for _ (underscores).
You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format. We can use the fortmat() string function in python to output the desired text in the order we want.
Check docs:
You are looking for:
>>> print '{0:>{x}}'.format('foo', x=x)
foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With