【问题标题】:How do I change a float into a string?如何将浮点数更改为字符串?
【发布时间】:2013-10-08 09:42:26
【问题描述】:

我试图创建一个属性生成器,我必须存储值。我唯一的问题是我存储的是浮点数而不是字符串,但我不知道如何更改它。

score = dtwo/done
print(int (score))
strength=score + initial

myFile = open( name + "'s Strength", 'wt')
myFile.write(strength)
myFile.close()

请帮忙,因为我一无所知....

【问题讨论】:

  • 使用str函数。

标签: python string python-3.x floating-point


【解决方案1】:

使用这个:

myFile.write(str(strength))

或者这个:

myFile.write(repr(strength))

指定位数:

myFile.write('{0:.5f}'.format(strength))

有关使用str.format 格式化的更多信息,请点击此处:http://docs.python.org/2/library/string.html#format-string-syntax

【讨论】:

    【解决方案2】:

    创建另一个变量,即字符串形式的strength。您将使用str 函数。

    other_variable=str(strength)
    

    那么不要将强度写入myFile,而是使用other_variable

    myFile.write(other_variable)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2019-01-07
      • 1970-01-01
      • 2014-07-31
      • 2011-11-25
      • 1970-01-01
      相关资源
      最近更新 更多