1

I want to format a string to a fixed width

If I use the following statement:

"{0:<8}".format(str(size)) #This one works

However,

# This one gives Invalid conversion specification
"{0:<width}".format(str(size)) 

Is there anyway to use a variable to format a string?

1
  • You could chain multiple formats together, but that would be ugly. Another way would be to just append to a string, or use one of the other ways to string format in addition to this. Commented Jul 1, 2015 at 17:51

2 Answers 2

6

Solution 1:
Use width to generate a string {0:<8} first

width = 8
("{0:<%d}"%width).format(s)

Solution 2:
Nested format:

"{0:<{1}}".format(s, width)

Named format maybe more readable:

"{string:<{width}}".format(string=s, width=width)

Solution 3:
Another way to translate {0:<8}: .ljust(8)

"{0}".format(s.ljust(width))

I choose 3. when
1) dealing with other encodings in i18n
2) print pretty

print 'a'.rjust(10, '-')
---------a
Sign up to request clarification or add additional context in comments.

Comments

2

It needs the actual value, not the string 'width'.

str(width).join(("{0:<", "}")).format(str(size)) 

Comments

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.