2014-02-20 72 views
1

我有可選的數字和字母,如'01a','b'和'02'的字符串。這些字符串總是有兩個部分,左邊的數字和右邊的字母。我想分開這些字符串來分別獲取數字和字母。我如何定義mySplit以獲得此結果?如何用數字和字母拆分Python字符串?

>>> map(mySplit, ['01123absd', 'bsdf', '02454']) 

[('01123', 'absd'), (None, 'bsdf'), ('02454', None)] 
+1

將它總是被格式化的數字則信嗎? – thegrinner

+0

會不會只有兩個部分? – LucasB

+0

是的,總會有兩個部分。 – msampaio

回答

2

您可以使用正則表達式這一點。我們要的是:

  • 以0個或多個數字開頭的字符串,
  • 以0或多個字母結尾的字符串。

注意,regex將創建一個名爲組的同時,還編制一次更有效率每次叫。

import re 
regex = re.compile("^(?P<numbers>\d*)(?P<letters>\w*)$") 

def myFunction(entry): 
    (numbers, letters) = regex.search(entry).groups() 
    return (numbers or None, letters or None) 

map(myFunction, ['01123absd', 'bsdf', '02454']) 

在最後一行的調用提供了以下的輸出:

[('01123', 'absd'), (None, 'bsdf'), ('02454', None)] 
0
import re 


def myFunction(t): 
    m = re.match(r"([a-z]*)([0-9]*)", t) 
    x,y = m.groups() 
    if x=='': x= None  
    if y=='': y= None  
    return ((x,y)) 

for s in ['01123absd', 'bsdf', '02454']: 
    print myFunction(s) 

生產:

(None, '01123') 
('bsdf', None) 
(None, '02454') 
1

如果你不想使用正則表達式,這是一個解決方案:

def split_num_str(my_str): 
    num = [x for x in my_str if x.isdigit()] 
    num = "".join(num) 

    if not num: 
     num = None 

    my_str = [x for x in my_str if x.isalpha()] 
    my_str = ''.join(my_str) 

    if not my_str: 
     my_str = None 

    return num, my_str 

m = map(split_num_str, ['01123absd', 'bsdf', '02454']) 
print m 

結果= [('01123', 'absd'), (None, 'bsdf'), ('02454', None)]

1

您可以使用正則表達式在這裏:

import re 

def myFunction(numbers_and_letters): 
    m = re.match(r"([a-z]*)([0-9]*)", numbers_and_letters) 
    return tuple(v == "" and None or v for v in m.groups()) 
+0

它不應該使用星號,因爲這兩種都不需要? – deinonychusaur

+0

是的,你是對的。我還需要將其更改爲無。 – apai

+0

'm.groups()中的返回元組(v ==「)和v的None或v)'' – deinonychusaur

2

到jramirez答案類似,只是有點短:

def myFunction(s): 
    return (''.join(c for c in s if c.isdigit()) or None, 
      ''.join(c for c in s if c.isalpha()) or None) 

print map(myFunction, ['01123absd', 'bsdf', '02454', '012abc345def']) 

輸出:

[('01123', 'absd'), (None, 'bsdf'), ('02454', None), ('', 'abcdef')]