Why Did My Loop Stop Iterating?
#newlist to add values to newlist = [] # iterate through characters in mystring for i in (mystring): # if a letter, append letter to newlist if i.isalpha(): newlist.
Solution 1:
You can use a regular expression to find groups of characters in brackets or just single characters. The regular expression will return tuples of matches - a match for each side of the regex 'or' (|
). For each tuple, only one of the strings will be filled, the other will be an empty string (hence the join
)
import re
mystring = 'AC[BC]D[ABD]'
[''.join(x) for x in re.findall(r'\[(\w+)\]|(\w)', mystring)]
# returns:
['A', 'C', 'BC', 'D', 'ABD']
Solution 2:
You can use regex
:
import re
mystring = 'AC[BC]D[ABD]'
final_data = re.findall('(?<=\[)\w+(?=\])|\w', mystring)
Output:
['A', 'C', 'BC', 'D', 'ABD']
Post a Comment for "Why Did My Loop Stop Iterating?"