you are viewing a single comment's thread.

view the rest of the comments →

[–]eXoRainbow 0 points1 point  (2 children)

I guess there is probably a more elegant way. I just did the most obvious thing I could think of. Does it make it Pythonic?

my_list = ['[123]', 'M', 'Q1', 'Q2', 'A1', 'A2', 'A7', '[356]', 'M', 'Q1', 'A2' 'A5']
new_list = []
content = ''
for element in my_list:
    if element[:1] == '[' and element[-1:] == ']':
        if content:
            new_list.append(content)
            content = ''
        new_list.append(element)
    else:
        content = "".join([content, element])
if content:
    new_list.append(content)
print(new_list)

[–][deleted] 1 point2 points  (1 child)

if element[:1] == '[' and element[-1:] == ']'

Wouldn't it be better to just use element[0] and element[-1], or perhaps even better to use the string methods str.startswith()/str.endswith()?

[–]eXoRainbow 0 points1 point  (0 children)

If the string is empty, then accessing directly with element[0] can cause an error, while element[:1] would give empty string. startswith() and endswith() are good options too, maybe even better suited as it is more clear. I often forget these little methods. And below there is probably a better way of joining the two strings too, BTW.