首页 > 解决方案 > 如何在python中获取替换度数符号

问题描述

我有一个字符串列表,其中一个元素看起来像“69.3°F”我想去掉整个列表的“°F”,以便将其转换为浮点数。

我试过了:

myTemps = myTemps.replace("°F", "")

myTemps = myTemps.replace(u"°F", "")

和 myTemps = [w.replace('°F','') for w in myTemps]

myTemps = [w.replace(u'°F','') for w in myTemps]

我不断回来

'list' object has no attribute 'replace'

关于我做错了什么的任何建议?

当我打印 MyTemps 我得到

['69.9  °F'], ['70.3  °F'], ['70.0  °F'], ['69.5  °F'],

myTemps 是由列表组成的列表

标签: pythonpandas

解决方案


对,如果你myTemps是一个字符串列表并且你想要一个浮点列表,

>>> temps = [['69.9  °F'], ['70.3  °F'], ['70.0  °F'], ['69.5  °F']]
>>> [float(l[0].replace('°F', '').strip()) for l in temps]
[69.9, 70.3, 70.0, 69.5]

推荐阅读