2016-02-11 71 views
0
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獲取類型錯誤

有什麼不對呢?爲什麼我得到一個字符串格式錯誤。我給出了兩個參數和兩個格式說明符。我做了一切都沒有元組通過它,但仍然無法正常工作。

+1

你的代碼格式出錯了。請參閱[Markdown幫助 - 代碼和預格式化文本](http://stackoverflow.com/editing-help#code)並請[編輯]您的文章。 –

回答

1

請參閱下文,以獲得使用os.path.join()構造文件路徑的更好方法。

對於直接的問題,元組中的2個參數僅與最後一個字符串'heu'相關聯。這是因爲%的運算符優先級高於+。因爲在'heu'沒有格式說明你的錯誤:

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 

你需要確保插值發生之前,你的字符串的其他組件進行評估。你可以做到這一點與括號:

>>> 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 

所以new_folder沒有規定:

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

或者你可以將元組直接到所需的字符串:

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

現在,考慮你實際上試圖做什麼,你可能會更好使用os.path.join()來把p ieces 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