Stanley Gan
Stanley Gan

Reputation: 481

How do I split strings based on a specific pattern using Python?

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.

Upvotes: 0

Views: 223

Answers (2)

masterfloda
masterfloda

Reputation: 3038

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))

Upvotes: 2

Wonjin
Wonjin

Reputation: 432

if you want to use regex library, you can just split by '\^'

re.split('\^', my_str)

# output : ['2a1', 'ath67e22', 'yz2p0']

Upvotes: -1

Related Questions