簡體   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