2016-01-08 42 views
0

我有一個Python列表,包含\x ASCII十六進制字符串字面值作爲一些元素和常規字符串。有沒有簡單的方法將這個列表分成兩種不同類型的字符串?下面的示例數據。Python將字符串拆分成兩個包含十六進制字符串和常規的字符串

我已經嘗試搜索字符串中的\x子字符串,但無法正常工作。

['\xFF', '\x42', 'A', '\xDE', '@', '\x1F']

編輯: 目前使用Python 2.7.9

這是我到目前爲止已經試過

>>> list=['\xFF', '\x42', 'A', '\xDE', '@', '\x1F'] 
>>> print [s for s in list if '\x' in s] 
ValueError: invalid \x escape 
>>> print [s for s in list if '\\x' in s] 
[] 
>>> print [s for s in list if '\x' in s] 
ValueError: invalid \x escape 
>>> print [s for s in list if 'x' in s] 
[] 
>>> 
+0

Python版本? –

+0

@IronFist編輯上面包括版本:2.7.9 – Matt

+0

它是如何「不能正常工作」?你不能讓它工作?或者你可以,但單靠這個測試還不足以將十六進制與其他條目區分開來? – TessellatingHeckler

回答

3

你可以使用一個列表理解與re.search。例如,要得到所有文字字符的新名單:

import re 
x = ['\xFF', '\x42', 'A', '\xDE', '@', '\1F'] 
print([i for i in x if re.search('\w',i)]) 

或者僅特定字符的ASCII碼範圍內分裂,是這樣的:

print([i for i in x if re.search('[\x05-\x40]',i)]) 

,我拿起上方的任意範圍。

+0

糟糕,我的範圍丟失了括號。固定。 – Brian

1

你可以看看每個字符串的repr,以確定它是否包含\x

xs = ['\xFF', '\x42', 'A', '\xDE', '@', '\1F', 'hello\xffworld'] 
hexes = []               
others = []              

for x in xs:              
    if r'\x' in repr(x):          
     hexes.append(x)           
    else:               
     others.append(x) 

print "hexes", hexes            
print "others", others            

輸出:

hexes ['\xff', '\xde', '\x01F', 'hello\xffworld'] 
others ['B', 'A', '@'] 
+0

這對''hello \ xffworld''不起作用 –

+0

@WayneWerner - 好的,我們可以直接使用'in'。 – pyrospade

0

我會假設你乾脆把非十六進制數字一起十六進制值。如果你想要一個十進制數的字符串(比如「25」)被拒絕,你可以檢查十六進制指示符後,你已經將它標識爲數字,如下所示:

看起來,How do I check if a string is a number (float) in Python?中顯示的代碼可能會這是一個很好的測試方法,只需循環並根據測試結果將字符串放在正確的列表中。

在[檢查Python字符串是否是數字]時也會顯示相同的函數(http://pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/ }

區別在於第二組代碼檢查unicode以及常規字符串強制轉換。

def is_number(s): 
    try: 
    float(s) 
    return True 
    except ValueError: 
    pass 

    try: 
    import unicodedata 
    unicodedata.numeric(s) 
    return True 
    except (TypeError, ValueError): 
     pass 

return False 
相關問題