Splitting a String in Python – Tutorial with Examples

In Python, a string can be split into a list of substrings using the split() method. The split method splits a string into a list based on a delimiter specified as an argument. By default, the split method uses white space characters as the delimiter, but you can specify any other character as the delimiter.

Syntax

string.split(separator, maxsplit)

Where:

  • string is the original string that you want to split
  • separator is an optional argument that specifies the delimiter character(s). If this argument is not specified, the default delimiter is white space characters
  • maxsplit is an optional argument that specifies the maximum number of splits to make. If this argument is not specified, all possible splits are made

Example 1: Splitting a String with the Default Delimiter

# Define a string
s = "Hello World"

# Split the string
words = s.split()

# Print the list of substrings
print(words)

Output:

['Hello', 'World']

In this example, the split method splits the string s into a list of substrings, using the default delimiter (white space characters). The resulting list words contains two substrings: 'Hello' and 'World'.

Example 2: Splitting a String with a Custom Delimiter

# Define a string
s = "Hello,World"

# Split the string using comma as the delimiter
words = s.split(",")

# Print the list of substrings
print(words)

Output:

['Hello', 'World']

In this example, the split method splits the string s into a list of substrings, using a comma as the delimiter. The resulting list words contains two substrings: 'Hello' and 'World'.

Example 3: Splitting a String with a Maximum Number of Splits

# Define a string
s = "Hello,World,How,Are,You"

# Split the string using comma as the delimiter
words = s.split(",", 3)

# Print the list of substrings
print(words)

Output:

['Hello', 'World', 'How', 'Are,You']

In this example, the split method splits the string s into a list of substrings, using a comma as the delimiter. The maxsplit argument is set to 3, which means that only the first three splits will be made. The resulting list words contains four substrings: 'Hello', 'World', 'How', and 'Are,You'.

Conclusion

In this article, we have seen how to split a string into a list of substrings in Python using the split() method. The split method is a simple and easy to use method that allows you to split a string based on a specified delimiter. You can also specify the maximum number of splits to make using the maxsplit argument. With the knowledge of splitting strings, you can easily manipulate and process text data in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *