uhexos
uhexos

Reputation: 391

How to set the spaces in a string format in Python 3

How can I set up the string format so that I could use a variable to ensure the length can change as needed? For example, lets say the length was 10 at first, then the input changes then length becomes 15. How would I get the format string to update?

    length =  0
    for i in self.rows:
        for j in i:
            if len(j) > length:
                length  = len(j)
    print('% length s')

Obviously the syntax above is wrong but I can't figure out how to get this to work.

Upvotes: 7

Views: 7520

Answers (4)

Mike Müller
Mike Müller

Reputation: 85462

The format method allows nice keyword arguments combined with positional arguments:

>>> s = 'my string'
>>> length = 20
>>> '{:>{length}s}'.format(s, length=length)
'           my string'

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191728

Using str.format

>>> length = 20
>>> string = "some string"
>>> print('{1:>{0}}'.format(length, string))
         some string

Upvotes: 9

tobias_k
tobias_k

Reputation: 82899

You can use %*s and pass in length as another parameter:

>>> length = 20
>>> string = "some string"
>>> print("%*s" % (length, string))
         some string

Or use a format string to create the format string:

>>> print(("%%%ds" % length) % string)
         some string

Upvotes: 5

armatita
armatita

Reputation: 13465

You can declare like this:

 print('%20s'%'stuff')

20 would be the number of characters in the print string. The excess in whitespace.

Upvotes: 0

Related Questions