2014-02-23 50 views
2

你好我怎麼可以從以下字符串如何從python中的給定字符串創建子字符串?

Netall_Low_Lin_kor_110_180 
Netall_Low_Lin_cer_110_181 
Netall_Low_Lin_asa_110_182 
Netall_Low_Lin_row_110_183 
Netall_Low_Lin_psq_182_42 
Netall_Low_Lin_vyt_182_41 

我想在這樣的方式「Netall_Low_Lin_kor」將是一個組成部分,「110_180」將成爲另一部分拆分上述字符串創建子。而對於「Netall_Low_Lin_psq_182_42」,我想將它分成「Netall_Low_Lin_psq」和「182_42」。

有什麼辦法可以分割這些字符串嗎?

回答

3
list_of_strings = [ 
"Netall_Low_Lin_kor_110_180", 
"Netall_Low_Lin_cer_110_181", 
"Netall_Low_Lin_asa_110_182", 
"Netall_Low_Lin_row_110_183", 
"Netall_Low_Lin_psq_182_42", 
"Netall_Low_Lin_vyt_182_41" 
] 

import re 
pattern = re.compile("_(?=\d+_\d+)") 
for current_string in list_of_strings: 
    print pattern.split(current_string) 

輸出

['Netall_Low_Lin_kor', '110_180'] 
['Netall_Low_Lin_cer', '110_181'] 
['Netall_Low_Lin_asa', '110_182'] 
['Netall_Low_Lin_row', '110_183'] 
['Netall_Low_Lin_psq', '182_42'] 
['Netall_Low_Lin_vyt', '182_41'] 

RegEx101 Demo + Explanation

2

有沒有必要使用正則表達式,如果子是固定大小的,用切片在這種情況下要簡單得多:

s = 'Netall_Low_Lin_kor_110_180' 
s[:18] 
=> Netall_Low_Lin_kor 
s[19:] 
=> 110_180 
相關問題