user18683
user18683

Reputation: 35

Getting TypeError during string formattion

key=12
head=851
file_pdf='pdf'

s=new_folder+'/'+file_pdf+'/'+'%s-%s.'+file_pdf+'heu'%(str(key),str(head),)

Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting

What is wrong in this? Why am I getting a string formatting error. I have given two arguments and two format specifiers. I did everything passed it without a tuple but still not working.

Upvotes: 0

Views: 57

Answers (1)

mhawke
mhawke

Reputation: 87054

See below for a better way to construct file paths using os.path.join().

For the immediate problem, the 2 arguments in the tuple are associated with the last string 'heu' only. This is because % has higher operator precedence than does +. Because there are no format specifiers in 'heu' you get the error:

key=12
head=851
file_pdf='pdf'

>>> 'heu' % (str(key), str(head),)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

You need to make sure that the other components of your string are evaluated before the interpolation occurs. You can do that with parentheses:

>>> s = (new_folder + '/' +file_pdf + '/' + '%s-%s.' + file_pdf + 'heu') % (str(key), str(head),)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'new_folder' is not defined

So new_folder is not specified:

>>> new_folder = 'blah'
>>> s = (new_folder + '/' +file_pdf + '/' + '%s-%s.' + file_pdf + 'heu') % (str(key), str(head),)
>>> print(s)
blah/pdf/12-851.pdfheu

Or you can apply the tuple directly to required string:

>>> s = new_folder + '/' +file_pdf + '/' + '%s-%s.' % (str(key), str(head),) + file_pdf + 'heu'

Now, considering what you are actually trying to do, you might be better off using os.path.join() to put the pieces together:

>>> import os.path
>>> s = os.path.join(new_folder, file_pdf, '%s-%s.%sheu' % (key, head, file_pdf))
>>> print(s)
blah/pdf/12-851.pdfheu

Upvotes: 1

Related Questions