我试图写骰子游戏分数到一个文件,但我得到这样的类型错误。TypeError:write()参数必须是str,而不是tup

2024-04-28 19:51:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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)

Tags: mostonfilewritehasscoretracebackrecent
3条回答

当你试图写一些东西到一个文件的方式,你做它必须是一个字符串,所以这就是为什么第一个失败。 第二个失败,因为(正如错误所说)您试图从未分组的元素中创建一个字符串。为了实现这一点,元素应该是onearray/list,这样Python就可以从中生成一个合适的字符串:

x = str(['on round',x,username1 ,'has',player1_score , '\n',username2'has', player2_score]) #See the square brackets

然而,更为Python式的方法是:

x = "on round %s %s has %d \n %s has %d" % (x, username1, player1_score, username2, player2score)

%s插入字符串,%d插入整数,%f插入浮点。请参阅Learn Python以获取对此的解释

应该是这样的:

x = 'on round {round} {user1} has {user1score} \n {user2} has {user2score}'.format(
round = x, user1 = username1, user1score = player1_score, user2= username2, user2score = player2_score)

使用.format()方法可以将值插入占位符,即round

嘿,你需要把x变量做成一个字符串格式。 您可以使用以下代码:

file = open("dicegamescores.txt","w") 
x = ('on round',2,username1 ,'has',player1_score , '\n',username2,'has', player2_score)
xx = ("%s%s%s%s%s%s%s%s%s")%(x)
file.write(xx) 
file.close

对于变量中的每个字符串,应添加%s。

相关问题 更多 >