如何使用str函数和字符串索引/切片将字符串转换为浮点值



标题可能有点令人困惑,但我的意思是说我有一个字符串s=" text, 7.4,text , 7.2, text,7.6,",我想取出数字7.4 7.2 7.6并将其转换为浮点值。如何仅使用简单的str函数(如find()或字符串索引/切片)来完成此操作?

我曾尝试使用replace()来删除所有逗号和单词,但我遇到了数字不间隔的问题:>>7.47.27.6,所以我无法转换为float;我不知道如何解释这一点,因为我的字符串的间距不一致。感谢

当项目无法转换为浮点时,您可以使用此代码并捕获异常:

l = []
for item in s.split(','):
try:
l.append(float(item.strip()))
except ValueError:
continue
print(l)
#[7.4, 7.2, 7.6]

您可以像这样一步一步地清理文本:

>>> s = " text, 7.4,text , 7.2,  text,7.6,"
>>> list_of_strings = [s.strip() for s in s.split(",") if s]
>>> list_of_strings
['text', '7.4', 'text', '7.2', 'text', '7.6']
>>> list_of_strings = [s for s in list_of_strings if not s.isalpha()]
>>> list_of_strings
['7.4', '7.2', '7.6']
>>> nums = [float(num) for num in list_of_strings]
>>> nums
[7.4, 7.2, 7.6]
>>>

或者,把它们放在一起:

>>> [float(elem.strip()) for elem in s.split(",") if elem and not elem.strip().isalpha()]
[7.4, 7.2, 7.6]
>>>

您可以这样做:

>>> [float(n) for n in s.split(',')[1::2]]

如果数字总是交替放置在字符串之间,那么您可以使用切片作为:

>>> s =" text, 7.4,text , 7.2,  text,7.6,"
>>> list(map(float, s.replace(" ", "").split(",")[1::2]))
[7.4, 7.2, 7.6]

以下是上述代码的逐步解释

  1. 首先使用my_str.replace(" ", "")删除所有空格
  2. 基于逗号,拆分列表以使用.split(',')获得单词列表
  3. 将您从start列表的切片作为1,将步骤作为2,以使用[1::2]获取数字字符串
  4. 使用map(float, <your_list>)键入列表中的所有数字

然而,如果数字随机分布在字符串中,那么您可以通过额外的条件检查来修改上述逻辑(这次使用列表理解),以将迭代期间的数字识别为:

>>> s =" text, 7.4, 9.5, text , 7.2, 8.6,text,7.6,"

>>> [float(n) for n in s.replace(" ", "").split(",") if n.replace('.','',1).isdigit()]
[7.4, 9.5, 7.2, 8.6, 7.6]

然而,在这种情况下,您不需要索引或切片。

最新更新