我在python3.7.2中创建了一个骰子游戏,我需要将结果写入一个文本文件,但是在当前格式下我得到了错误
我试着用一根弦来弹,但那只会引起更多的问题
file = open("dicegamescores.txt","w")
x = str('on round',x,username1 ,'has',player1_score , '\n',username2'has', player2_score)
file.write(x)
file.close
我期望('on round',x,username1,'has',player1\u score,'\n',username2,'has',player2\u score)根据迭代使用正确的变量值写入文件 但我明白了:
不强制转换为STR时:
Traceback (most recent call last):
File "C:\Users\joelb\AppData\Local\Programs\Python\Python37\dicegame.py", line 45, in <module>
file.write(x)
TypeError: write() argument must be str, not tuple
或者当我投STR的时候:
Traceback (most recent call last):
File "C:\Users\joelb\AppData\Local\Programs\Python\Python37\dicegame.py", line 44, in <module>
x = str('on round', x, username1 , 'has', player1_score , '\n' , username2 , 'has', player2_score )
TypeError: str() takes at most 3 arguments (9 given)
当你试图写一些东西到一个文件的方式,你做它必须是一个字符串,所以这就是为什么第一个失败。 第二个失败,因为(正如错误所说)您试图从未分组的元素中创建一个字符串。为了实现这一点,元素应该是onearray/list,这样Python就可以从中生成一个合适的字符串:
然而,更为Python式的方法是:
%s插入字符串,%d插入整数,%f插入浮点。请参阅Learn Python以获取对此的解释
应该是这样的:
使用
.format()
方法可以将值插入占位符,即round
嘿,你需要把x变量做成一个字符串格式。 您可以使用以下代码:
对于变量中的每个字符串,应添加%s。
相关问题 更多 >
编程相关推荐