How to Split Strings into Substrings in Python?

Estimated read time 1 min read

In Python, you can use the split() method to split a string into substrings based on a delimiter. The split() method returns a list of substrings.

Here is an example of how to use the split() method:

string = "Hello, World!"
substr_list = string.split(", ")  # Split the string at the comma and space

print(substr_list)  # Output: ['Hello', 'World!']

In this example, the split() method is called on the string variable with the delimiter “, ” (a comma followed by a space). This splits the string into two substrings, “Hello” and “World!”, and returns them as a list.

You can also split a string based on other delimiters such as spaces or tabs. Here’s an example:

string = "apple, banana, cherry"
substr_list = string.split(", ")  # Split the string at the comma and space

print(substr_list)  # Output: ['apple', 'banana', 'cherry']

In this example, the split() method is called with the delimiter “, “. This splits the string into three substrings, “apple”, “banana”, and “cherry”, and returns them as a list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply