Why do I get "TypeError: not all arguments converted during string formatting" when trying to build a template string and then interpolate using %?

Question:

There are a lot entries, according to:”TypeError: not all arguments converted during string formatting” but I don’t found the reason, why this:

print("File: %30s "%("name"))

is working, but not this:

leng=30
print("File: %"+ str(leng) +"s "%("name"))    
Asked By: rundekugel

||

Answers:

Because of order of operations, your code evaluates as:

"File: %" + str(leng) + ("s "%("name"))

To fix this, just parenthesize the string like:

("File" + ...)%("name")
Answered By: internet_user

The latter one applies % only to "s ". Use grouping parentheses:

print(("File: %" + str(leng) + "s ") % "name")    
Answered By: deceze

Instead you could do

print("File: {:.30}".format(name))

where name is a predefined filename

Answered By: Robbie Milejczak

Not really related to OP’ request, but using python3.6 f-strings, you can avoid using two levels of string in-place replacement; here is an example:

>>> filename = "some name"    
>>> print(f"File: {filename:-^{len(filename)+6}} ")
---some name---

For older versions of python, the other answers apply.

Answered By: Joël
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.