2017-06-04 28 views
0

比方說,我有這個字符串'foo1bar2xyz'將字符串拆分爲文本和數字?

我知道數字索引以它{'1': 3, '2': 7}

我想形成不具有數字父串子。我將如何獲得刪除特定索引的字符串的子字符串?

其中在上述情況下,這將是['foo', 'bar', 'xyz']

是否嘗試過這個至今

def iterate_string(og_string, start, stop): 
    if start == 0: 
     return og_string[:stop] 
    else: 
     return og_string[start+1:stop] 

def ret_string(S): 
    digit_dict = {c:i for i,c in enumerate(S) if c.isdigit()} 
    digit_positions = list(digit_dict.values()) 
    # return digit_positions 
    substrings = [] 
    start_index = 0 
    for position in digit_positions: 
     p = iterate_string(S, start_index, position) 
     substrings.append(p) 
     start_index = position 

    return substrings 


print ret_string('foo1bar2xyz') 

但這返回['foo', 'bar']

相關SOquestions

+0

的[如何分割字符串轉換爲文本和數字可能重複? ](https://stackoverflow.com/questions/430079/how-to-split-strings-into-text-and-number) –

+0

在你的代碼中,除非最後一個字符是數字,否則不會得到期望的輸出。如果start_index是最後一個索引,則必須檢查for循環。如果不附加'S [start_index + 1:]'。但是,如果最後一個字符是數字,您可能需要考慮回答 – kuro

回答

2

試試這個:

l = re.compile("[0-9]").split(s) 
4

可以使用RE做

import re 
h = "foo1bar2xyz" 
l = re.compile("\d").split(h) 

輸出:

['foo', 'bar', 'xyz'] 
2

如果有指數,並希望作爲輸入使用,那麼這是一個好主意太:

def split_by_indices(s, indices): 
    ends = sorted(indices.values()) # we only need the positions 
    ends.append(len(s)) 
    substrings = [] 
    start = 0 
    for end in ends: 
     substrings.append(s[start:end]) 
     start = end + 1 
    return substrings 

演示:

>>> split_by_indices('foo1bar2xyz', {'1': 3, '2': 7}) 
['foo', 'bar', 'xyz'] 

忽略輸入字符串任何實際的數值,並從你的字典裏只有使用[3, 7]位置。

但是,如果你正在構建{'1': 3, '2': 7}地圖只是分割你的字符串,它可能是更容易,只需使用正則表達式:

import re 

split_by_digits = re.compile(r'\d').split 
result = split_by_digits(inputstring) 
+0

中描述的方式,第一種方法將在輸出 – kuro

+0

@kuro中給出一個空字符串:另一種方法也是如此。這取決於你的用例,如果這需要或不。 –