How to split a Python string into a list

Share

The split() method​ in Python breaks a string down into a list of substrings using a specified separator. The method does not alter the original string; instead, a new list of substrings is returned.

Syntax

str.split(separator, maxSplit)
  • The string splits at the specified separator. If a separator is not provided, then the string is split on every white-space.
  • maxSplit is an integer that specifies the maximum number of times the string can be split. If it is not specified, then there is no upper limit.
svg viewer

Code

The following code snippet demonstrates how the split() method is used. ​

str1 = "hi, this is, educative"
# Without any arguments, the separator is a white-space.
print("Split using default separator:", str1.split())
print("Split using ',' as a seperator:", str1.split(','))
# Setting maxSplit to 1 means the string is only split once.
print("Split using ',' as a seperator with maxSplit:", str1.split(',', 1))
Copyright ©2024 Educative, Inc. All rights reserved