7

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.

5
  • Can you fix your indentation? Are you trying to print within the for loop? Commented Mar 21, 2016 at 18:36
  • 1
    please show example input and expected output. Commented Mar 21, 2016 at 18:37
  • Why wouldn't you just use print(s)? It will print whatever s is. Commented Mar 21, 2016 at 18:43
  • BTW, you can replace that nested loop with max(map(len, (j for i in rows for j in i))) Commented Mar 21, 2016 at 18:52
  • @tobias_k shorter and more readable way: max(len(j) for i in rows for j in i) Commented Jul 27, 2022 at 7:57

4 Answers 4

9

Using str.format

>>> length = 20
>>> string = "some string"
>>> print('{1:>{0}}'.format(length, string))
         some string
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

1

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

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

Comments

0

You can declare like this:

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

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

4 Comments

length changes the amount of white space, it isnt what gets printed
I just printed it. I'm pretty sure I'm seeing white space.
The OP is trying to get a format string that does not depend on knowing the length ahead of time. He wants to be able to change the length, but use the same format string. tobias_k's answer should give you the idea.
tobias_k answer is indeed a more complete example (although the solution is the same,... I think). Should I delete my post?

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.