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"))
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")
The latter one applies %
only to "s "
. Use grouping parentheses:
print(("File: %" + str(leng) + "s ") % "name")
Instead you could do
print("File: {:.30}".format(name))
where name is a predefined filename
Not really related to OP’ request, but using python3.6
f-string
s, 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.
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"))
Because of order of operations, your code evaluates as:
"File: %" + str(leng) + ("s "%("name"))
To fix this, just parenthesize the string like:
("File" + ...)%("name")
The latter one applies %
only to "s "
. Use grouping parentheses:
print(("File: %" + str(leng) + "s ") % "name")
Instead you could do
print("File: {:.30}".format(name))
where name is a predefined filename
Not really related to OP’ request, but using python3.6
f-string
s, 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.