Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format align using a variable?

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')
like image 704
vesche Avatar asked Mar 02 '17 15:03

vesche


People also ask

How do you align variables in Python?

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.

Can you format a variable python?

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".

How do you format a variable name?

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).

How do I format a right align in Python?

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.


1 Answers

Check docs:

You are looking for:

>>> print '{0:>{x}}'.format('foo', x=x)
       foo
like image 183
xiº Avatar answered Oct 07 '22 02:10

xiº