Last modified: Feb 14, 2023 By Alexander Williams
Python Split By Multiple Characters
To split by multiple characters, You can need to choose between:
- re.split() method
- re.findall() method
- str.split() method
This article will explore how to split by multiple characters using each method.
1. re.split() method
The re module in Python provides a method split, which can be used to split a string based on multiple characters.
Syntax:
re.split(pattern, string, maxsplit=0, flags=0)
patternIs a regular expression.stringIs the input string that needs to be split.maxsplit(optional) is the maximum number of splits.flags(optional) is an optional parameter used to modify the behavior of the pattern.
In this example, we'll split a string by multiple characters.
import re
string = "apple,banana;cherry,date" # String
delimiters = "[,;]" # delimiters
result = re.split(delimiters, string) # Split By Multiple Characters
print(result) # Print Result
Output:
['apple', 'banana', 'cherry', 'date']
However, In the above example, we have split the string by , and ; characters as delimiters.
2. str.split method
spilt() is a method used to split a string based on a single character. In the following example, we'll see how to split by multiple characters using this method.
string = "apple,banana;cherry,date" # String
delimiters = ",;" # delimiters
result = ""
for delimiter in delimiters: # Loop through the delimiters
result = [part.split(delimiter) for part in result] # Split the string using the current delimiter
result = [item for sublist in result for item in sublist] # Flatten the list of sublists into a single list
print(result) # Print Result
In the above example, we have used the str.split method multiple times to split the string based on each character in the delimiters list. This results in the final list that contains the parts of the string after splitting based on all the characters in the delimiters list.
3. re.findall() method
We can also use the re.findall() method to split a string by multiple characters. Let's see the syntax and the example:
Syntax:
re.findall(pattern, string, flags=0)
Here is an example:
import re
string = "apple,banana;cherry,date"
delimiters = "[,;]"
result = re.split(delimiters, string)
print(result)
Output: ['apple', 'banana', 'cherry', 'date']
Output:
['apple', 'banana', 'cherry', 'date']
As you can see, the example above is simliare to the re.split example.
Conclusion
In conclusion, splitting a string by multiple characters can be done in Python using the re.split method, the re.findall method, or the str.split method with some modifications.
Each method has its own benefits. For example, when dealing with complex string manipulations, using regular expressions with the re module can be more flexible and efficient.