Python split on multiple characters

Python Split on Multiple Characters

The split() method in Python is used to split a string into a list of substrings based on a specified separator. By default, the separator is a space character. However, if you want to split the string on multiple characters, you can pass a string containing all the characters as the separator.

Here’s an example:

    
    sentence = "Hello-World;Welcome:to,Python"
    separator = "-:;,"
    result = sentence.split(separator)
    print(result)
    
  

In this example, we have a sentence that contains various separators such as hyphen, colon, semicolon, and comma. We define a variable ‘separator’ that contains all these characters. Then, we use the split() method on the ‘sentence’ string, passing the ‘separator’ variable as the argument. The method splits the string into substrings at each occurrence of any character in the separator. The result is a list of substrings.

The output of the above code will be:

    
    ['Hello', 'World', 'Welcome', 'to', 'Python']
    
  

As you can see, the original sentence is split into individual words, excluding all the separators.

You can customize the separator string based on your requirement. By including multiple characters in the separator string, you can split the string on any combination of those characters.

Leave a comment