2016-11-27 41 views
0

我試圖創建一個函數,將返回輸入的字符串的浮力和浮動。但會刪除包含任何非數字字符的單詞。目前,我已經得到它返回只有數字,但它不是返回花車爲浮動返回浮動和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

你的代碼根本不起作用。在你的正則表達式中,你似乎在第一個選擇中混淆了反斜槓。 –

回答

0

這應該工作:

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

它使用\b邊界類,而你是雙\\逃逸

0

這樣的事情呢?

正則表達式匹配空格分隔的單詞,只有數字字符和可能的單個點。然後將所有內容轉換爲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]) 
0

您可以迭代每個值並嘗試將其轉換爲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]