⊗pyPmREMSp 69 of 128 menu

The split method in Python regular expressions

To split a string according to a specified regular expression, use the split method. In the first parameter of the method, we specify the regular expression by which we will split the string. In the second parameter, we specify the string that we need to split. In the third optional parameter, you can specify the maximum number of parts to split. The method returns a list of parts of the split string:

re.split(what we break, where we break, [max. number of parts])

Example

Let's split the line at the hyphen:

txt = 'aaa-bbb-123 456' res = re.split('-', txt) print(res)

Result of code execution:

['aaa', 'bbb', '123 456']

Example

Now let's split the line at the hyphen twice:

txt = 'aaa-bbb-123-456' res = re.split('-', txt, 2) print(res)

As can be seen from the code execution result, the string was split at the hyphen only into two parts. And the third part of the string included its remainder:

['aaa', 'bbb', '123-456']

Practical tasks

Given a string with date and time:

txt = '2025-12-31 12:59:59'

Split this string so that all year, month, day, hours, minutes and seconds are in one array.

byenru