我有一个看起来像这样的字符串:
a = "'92.345'\r\n\r\n"
a.strip()
当我尝试使用 np.float(a)
或仅使用 float(a)
将其转换为 float 时,我得到了
*** Value error: could not convert string to float: '92.345'
如何将它干净地转换为 float ?
最佳答案
您需要strip您的字符串以删除空格和一个引号 '
:
>>> float(a.strip().strip("'"))
92.345
或者正如@Martijn Pieters 在评论中所说,您可以使用 a.strip("\r\n\t '")
将其减少为一个 strip 调用。
关于Python 将字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219479/