繁体   English   中英

如何在 python 中获取替换度符号

[英]How to get replace degree symbol in 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 是由列表组成的列表

对,如果你的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]

您可以使用map中的 map function 替换列表中所有元素的度数符号。

def ReplaceDegrees(temperature):
    return temperature.replace("°F", "")

myTemps = ["12°F", "56°F", "112°F"]
myTemps = list(map(ReplaceDegrees, myTemps))

For more on the map function see https://www.w3schools.com/python/ref_func_map.asp or https://docs.python.org/3/library/functions.html#map

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM