With a RegEx, you can find key,value
pairs, store them in a dictionary, and print them out:
import re
mystr = "[aaa ] some text here [bbbb3 ] some other text here [cc ] more text"
a = dict(re.findall(r"\[([A-Za-z0-9_\s]+)\]([A-Za-z0-9_\s]+(?=\[|$))", mystr))
for key, value in a.items():
print key, value
# OUTPUT:
# aaa some text here
# cc more text
# bbbb3 some other text here
The RegEx matches 2 groups:
The first group is all the characters, numbers and spaces inside enclosed in squared brackets and the second is all the characters, numbers and spaces preceded by a closed square bracket and followed by an open square brackets or end of the line
First group: \[([A-Za-z0-9_\s]+)\]
Second group: ([A-Za-z0-9_\s]+(?=\[|$))
Note that in the second group we have a positive lookahead: (?=\[|$)
. Without the positive lookahead, the character would be consumed, and the next group won't find the starting square bracket.
findall returns then a list of tuple: [(key1,value1), (key2,value2), (key3,value3),...]
.
A list of tuple can be immediately converted into a dictionary: dict(my_tuple_list).
Once you have your dict, you can do what you want with your key/value pairs :)