split
Lesson 4 of 28 in Coddy's RegEx in Python course.
The split function allows you to split a string into a list based on a specified pattern. It's similar to the split method for strings, but with more powerful pattern matching capabilities.
re.split(pattern, string, maxsplit=0)- pattern: The regular expression pattern to split the string by.
- string: The string to be split.
- maxsplit: Optional. The maximum number of splits to perform. The default value is 0, which means no limit on the number of splits
import re
text = "one, two, three, four"
pattern = ", "
result = re.split(pattern, text)
print(result) # Output: ['one', 'two', 'three', 'four']In the above example, we used the split function to split the string text wherever there is a comma followed by a space. The result is a list of the split substring
Challenge
EasyWrite a program that uses the split function to split the string "apple;banana;cherry;date" into a list of fruits. Use the semicolon ; as the delimiter. Print the result at the end.
Try it yourself
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction