我有一个Python字符串
string = aaa1bbb1ccc1ddd
我希望像这样分开它
re.split('[split at all occurrences of "1", unless the 1 is followed by a c]', string)
所以结果是
['aaa', 'bbb1ccc', 'ddd']
我该怎么做?
答案 0 :(得分:8)
对正则表达式和re
模块使用负向前瞻:
>>> string = 'aaa1bbb1ccc1ddd'
>>> import re
>>> re.split(r"1(?!c)", string)
['aaa', 'bbb1ccc', 'ddd']
答案 1 :(得分:3)
def split_by_delim_except(s, delim, bar):
escape = '\b'
find = delim + bar
return map(lambda s: s.replace(escape, find),
s.replace(find, escape).split(delim))
split_by_delim_except('aaa1bbb1ccc1ddd', '1', 'c')
答案 2 :(得分:0)
虽然不如正则表达式那么漂亮,但我的以下代码返回相同的结果:
string = 'aaa1bbb1ccc1ddd'
p1 = string.split('1')
new_result = []
count = 0
for j in p1:
if j.startswith('c'):
# This removes the previous element from the list and stores it in a variable.
prev_element = new_result.pop(count-1)
prev_one_plus_j = prev_element + '1' + j
new_result.append(prev_one_plus_j)
else:
new_result.append(j)
count += 1
print (new_result)
[' aaa',' bbb1ccc',' ddd']