Andrius
Andrius

Reputation: 21118

Python - use format string length variable instead of fixed one?

For example I can do this:

"%.2s" % ('aaa')
'aa'

or

"%.1s" % ('aaa')
'a'

But how can I make that part like .2 variable, so I could pass any number and it would format accordingly, like if I would pass something like:

"%.%ss %" (1, 'aaa') # Pseudo code
'a'

Upvotes: 1

Views: 164

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121804

Specify the width as * and the actual width will be taken from the next positional argument:

"%.*s" % (1, 'aaa')

The str.format() method is more flexible still, you can interpolate any parameter, not just the width:

"{:.{width}s}".format('aaa', width=1)

Demo:

>>> "%.*s" % (1, 'aaa')
'a'
>>> "%.*s" % (2, 'aaa')
'aa'
>>> "{:.{width}s}".format('aaa', width=1)
'a'
>>> "{:.{width}s}".format('aaa', width=2)
'aa'

The extra placeholders can be used for any element making up the format specification:

>>> "{:{align}{width}s}".format('aaa', align='<', width=4)
'aaa '
>>> "{:{align}{width}s}".format('aaa', align='>', width=4)
' aaa'

Upvotes: 4

Related Questions