How to Split a String in Python

09/11/2021

Contents

In this article, you will learn how to split a string in Python.

How to split a string

In Python, you can split a string into a list of substrings using the split() method. The split() method splits a string into substrings based on a specified delimiter, such as a space, comma, or any other character or string you choose.

Here’s an example:

# Split a string with space delimiter
my_string = "Hello world, how are you?"
my_list = my_string.split()
print(my_list) # Output: ['Hello', 'world,', 'how', 'are', 'you?']

# Split a string with comma delimiter
my_string = "apple, banana, orange"
my_list = my_string.split(",")
print(my_list) # Output: ['apple', ' banana', ' orange']

By default, the split() method splits the string on whitespace characters (spaces, tabs, and newlines), but you can pass in any delimiter you want as an argument to the split() method.

Additionally, you can also specify the maximum number of splits to be made using the maxsplit argument. For example:

# Split a string with maxsplit
my_string = "apple, banana, orange, grapes"
my_list = my_string.split(", ", maxsplit=2)
print(my_list) # Output: ['apple', 'banana', 'orange, grapes']

In this example, the string is split at the first two occurrences of the comma followed by a space, so the resulting list contains three elements.

 

Here are a few more things to keep in mind when working with the split() method in Python:

  • If you call the split() method without any arguments, it will split the string on whitespace characters by default.
  • The split() method returns a list of substrings, which you can assign to a variable and use later in your code.
  • If the delimiter you pass to the split() method is not found in the string, it will return the original string as a single-element list.

If you want to split a string into individual characters, you can use the list() function instead of the split() method. For example:

# Split a string into individual characters
my_string = "hello"
my_list = list(my_string)
print(my_list) # Output: ['h', 'e', 'l', 'l', 'o']

If you want to split a string into lines, you can use the splitlines() method. This method splits the string at line breaks (i.e., the \n character) and returns a list of lines. For example:

# Split a string into lines
my_string = "Line 1\nLine 2\nLine 3"
my_list = my_string.splitlines()
print(my_list) # Output: ['Line 1', 'Line 2', 'Line 3']