【发布时间】:2018-11-20 11:13:31
【问题描述】:
给定一个示例字符串s = 'Hi, my name is Humpty-Dumpty, from "Alice, Through the Looking Glass"',我想将它分成以下几个块:
# To Do: something like {l = s.split(',')}
l = ['Hi', 'my name is Humpty-Dumpty', '"Alice, Through the Looking Glass"']
我不知道我会在哪里找到多少个分隔符。
这是我最初的想法,它很长,而且不准确,因为它删除了所有分隔符,而我希望引号内的分隔符能够保留:
s = 'Hi, my name is Humpty-Dumpty, from "Alice, Through the Looking Glass"'
ss = []
inner_string = ""
delimiter = ','
for item in s.split(delimiter):
if not inner_string:
if '\"' not in item: # regullar string. not intersting
ss.append(item)
else:
inner_string += item # start inner string
elif inner_string:
inner_string += item
if '\"' in item: # end inner string
ss.append(inner_string)
inner_string = ""
else: # middle of inner string
pass
print(ss)
# prints ['Hi', ' my name is Humpty-Dumpty', ' from "Alice Through the Looking Glass"'] which is OK-ish
【问题讨论】:
标签: python python-3.x split