Python 类型错误:不支持解码 str
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40208812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: decoding str is not supported
提问by Lomore
Im trying to make a attribute characteristic randomiser for my nephews board game and I'm trying to write the attributes to an external file so that he can use them later. when i am trying to write to the file it comes up with the error
我正在尝试为我的侄子棋盘游戏制作一个属性特征随机器,我正在尝试将属性写入外部文件,以便他以后可以使用它们。当我尝试写入文件时出现错误
speedE = str('Speed -', str(speed))
TypeError: decoding str is not supported
my code is adding the calculated attribute to the name of the attribute. I.E. ('Strength - ', strengthE) my code is ...
我的代码正在将计算的属性添加到属性的名称中。IE ('Strength - ', strengthE) 我的代码是...
import random
char1 = open('Character1.txt', 'w')
strength = 10
strength += int(random.randint(1, 12) / random.randint(1,4))
speed = 10
speed += int(random.randint(1, 12) / random.randint(1,4))
speedE = str('Speed -', str(speed))
char1.write(speedE)
strengthE = str('Strength -', str(strength))
char1.write(strengthE)
print(char1)
char1.close()
char2 = open('Character2.txt', 'w')
strength2 = 10
strength2 += int(random.randint(1, 12) / random.randint(1,4))
speed2 = 10
speed += int(random.randint(1, 12) / random.randint(1,4))
speedE2 = str('Speed -', str(speed))
char2.write(speedE2)
strengthE2 = str('Strength -', str(strength))
char2.write(strengthE2)
print(char1)
char2.close()
im quite new to writing to external files and its not going too well aha. me and my nephew would really appreciate it if you could help, Thanks
我对写入外部文件很陌生,而且不太顺利啊哈。如果您能提供帮助,我和我的侄子将不胜感激,谢谢
采纳答案by Moses Koledoye
Not sure about what you expect str('Speed -', str(speed))
to do.
不确定你期望str('Speed -', str(speed))
做什么。
What you want is a string concat:
你想要的是一个字符串连接:
speedE2 = 'Speed -' + str(speed)
# replace other lines also
You can also use string formatting and not worry about type casts:
您还可以使用字符串格式,而不必担心类型转换:
speedE2 = 'Speed -{}'.format(speed)