2017-07-06 30 views
3

我試圖將包含2個浮點數和3個文本部分的元組轉換爲一個字符串,所以我可以在file.write()中使用它,因爲它不是接受元組。將浮點數和文本組成的元組轉換爲單個字符串

testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters' 
test = open('testresults.txt' ,'w') 
test.write(testr) 
test.close() 

每當我嘗試運行它給了我這個

test.write(testr) 
TypeError: must be str, not tuple 

回答

1

不像其他的答案,這將花費你提出的元組:

testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters' 
test = open('testresults.txt' ,'w') 
test.write(" ".join(str(i)for i in testr)) 
test.close() 

由於只有第三行是從您的代碼不同,這裏有雲的解釋:

第一str(i)for i in testr

inline for -loop在Python中被稱爲list comprhension。它只是迭代你的testr元組,逐個返回值。 str(i)是一個類型轉換,它試圖將i轉換爲一個字符串。這是必要的,因爲在你的元組中有些條目是String類型,而一些變量是某種類型的數字,可能是FloatInteger。請參閱str()float()int()以供進一步閱讀。

然後" ".join(...)

這是字符串類型需要字符串列表或數組和,作爲名稱sugests的函數,聯接一起通過它作用在子串,在前面的部分分隔點(" ")。這對我來說總是感覺有點奇怪,或者也許是內在的,但它仍然是一個非常有用的功能!

我希望這有助於!

+0

謝謝它的工作!有沒有可能你可以解釋這是如何工作的?所以我可以用其他方式或其他項目來工作。 –

2

使用format程序:

testr = 'you went {} mph and stopped in {} meters'.format(speed, stop) 
0

將其轉換爲String

test.write(str(testr)) 
+1

這只是創建了元組的視覺表示。不是乾淨的句子... – Kraay89

0

值得慶幸的是,蟒蛇3.6使得硫人很容易和可讀性爲我們:

testr = f'you went {speed} mph and stopped in {stop} metres' 
test = open('testresults.txt' ,'w') 
test.write(testr) 
test.close() 

否則,同樣的事情通過使用string.format(*args)在另一個答覆中提到來達到的。

+0

和python2怎麼樣? – Netwave

相關問題