My string is of the form my_str = "2a1^ath67e22^yz2p0". I would like to split based on the pattern '^(any characters) and get ["2a1", "67e22", "2p0"]. The pattern could also appear in the front or the back part of the string, such as ^abc27e4 or 27c2^abc. I tried re.split("(.*)\^[a-z]{1,100}(.*)", my_str) but it only splits one of those patterns. I am assuming here that the number of characters appearing after ^ will not be larger than 100.
2 Answers
you don't need regex for simple string operations, you can use
my_list = my_str.split('^')
EDIT: sorry, I just saw that you don't want to split just on the ^ character but also on strings following. Therefore you will need regex.
my_list = re.split('\^[a-z]+', my_str)
If the pattern is at the front or the end of the string, this will create an empty list element. you can remove them with
my_list = list(filter(None, my_list))
1 Comment
Stanley Gan
Thanks a lot! Didn't know it was that easy haha
r"\^[a-z]+should be sufficient.