Python 类型错误:必须是 str,而不是浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20162664/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:42:50  来源:igfitidea点击:

TypeError: must be str, not float

pythonstring

提问by user3024763

this is 1/8 of my script:

这是我脚本的 1/8:

print('Your skill:', int(charskill))
with open('C:\Documents and Settings\Welcome\My Documents\python\Task 2\lol.txt', 'w') as myFile:
    myFile.write(charskill)

Once I execute on python, it gives me an error of:

一旦我在 python 上执行,它会给我一个错误:

Traceback (most recent call last):
  File "C:\Documents and Settings\Welcome\My Documents\python\Task 2\Dice generator v2.py", line 39, in <module>
    myFile.write(charskill)
TypeError: must be str, not float

How do I fix this problem? I want the file to run on notepad ;/ because it is my homework at school.

我该如何解决这个问题?我希望该文件在记事本上运行;/ 因为这是我在学校的作业。

采纳答案by Jon Clements

If you're using Python 3.x (it's possible you might be given your print), then instead of using .writeor string formatting, an alternative is to use:

如果您使用的是 Python 3.x(您可能会得到您的print),那么除了使用.write或 字符串格式之外,另一种方法是使用:

print('Your Skill:', charskill, file=myFile)

This has the advantage of putting a space in there, and a newline character for you and not requiring any explicit conversions.

这具有在其中放置一个空格和一个换行符的优点,并且不需要任何显式转换。

回答by falsetru

You should pass strobject to file.write. But it seems like charskillis floatobject.

您应该将str对象传递给file.write. 但它似乎charskillfloat对象。

Replace following line:

替换以下行:

myFile.write(charskill)

with:

和:

myFile.write(str(charskill)) # OR   myFile.write(str(charskill) + '\n')

or

或者

myFile.write('{}'.format(charskill)) # OR  myFile.write('{}\n'.format(charskill))

to convert floatto str.

转换floatstr.

回答by zjm555

Try casting your float to a string before writing it:

在写入之前尝试将浮点数转换为字符串:

myFile.write(str(charskill))