返回浮动和int在一个混合输入python的字符串

问题描述:

我试图创建一个函数,将返回输入的字符串的浮力和浮动。但会删除包含任何非数字字符的单词。目前,我已经得到它返回只有数字,但它不是返回花车为浮动返回浮动和int在一个混合输入python的字符串

float_sort=0.2 2.1 3.1 ab 3 c abc23 
float_sort = "".join(re.findall(r"d+\.\\d+|\d+", float_sort)) 

#Actual results 2,2,1,3,1,3,2,3 
#desired results: 0.2,2.1,3.1,3 
+0

运算符优先级指示您的'|'不会按您的想法行事。 – njzk2

+0

你的代码根本不起作用。在你的正则表达式中,你似乎在第一个选择中混淆了反斜杠。 –

这应该工作:

re.findall(r"\b(\d+\.\d+|\d+)\b", float_sort) 

它使用\b边界类,而你是双\\逃逸

这样的事情呢?

正则表达式匹配空格分隔的单词,只有数字字符和可能的单个点。然后将所有内容转换为float,然后将可以表示为int的内容转换为int。最后一步是必要的,如果你确实需要这些数字为int出于某种原因。

import re 

float_sort = '0.2 2.1 3.1 ab 3 c abc23' 
split = re.findall(r"\b(\d+\.\d+|\d+)\b", float_sort) 
print(float_sort) 

split = [float(x) for x in split] 
split = [int(x) if x == int(x) else x for x in split] 

print(split) 
print([type(x) for x in split]) 

您可以迭代每个值并尝试将其转换为float或int。如果我们无法将其转换,那么我们不会将其包含在我们的最终输出中。字符串有一些有用的功能,允许我们确定字符串是否可能代表intfloat

# split each element on the space 
l = float_sort.split() 

# for each element, try and convert it to a float 
# and add it into the `converted` list 
converted = [] 
for i in l: 
    try: 
     # check if the string is all numeric. In that case, it can be an int 
     # otherwise, it could be a float  
     if i.isnumeric(): 
      converted.append(int(i)) 
     else: 
     converted.append(float(i)) 
    except ValueError: 
     pass 

    # [0.2, 2.1, 3.1, 3]