1

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'
1

1 Answer 1

4

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. Thanks. Both solutions are good, though first one seems like is more readable in this case (at least for me).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.