比方說,我有這個字符串'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']
的[如何分割字符串轉換爲文本和數字可能重複? ](https://stackoverflow.com/questions/430079/how-to-split-strings-into-text-and-number) –
在你的代碼中,除非最後一個字符是數字,否則不會得到期望的輸出。如果start_index是最後一個索引,則必須檢查for循環。如果不附加'S [start_index + 1:]'。但是,如果最後一個字符是數字,您可能需要考慮回答 – kuro