freeCodeCamp/guide/english/python/string-methods/string-split-method/index.md

1.7 KiB

title
String Split Method

The split() function is commonly used for string splitting in Python.

The split() method

Template: string.split(separator, maxsplit)

separator: The delimiter string. You split the string based on this character. For eg. it could be " ", ":", ";" etc

maxsplit: The number of times to split the string based on the separator. If not specified or -1, the string is split based on all occurrences of the separator

This method returns a list of substrings delimited by the separator

Examples

  1. Split string on space: " "
string = "freeCodeCamp is fun."
print(string.split(" "))

Output:

['freeCodeCamp', 'is', 'fun.']
  1. Split string on comma: ","
string = "freeCodeCamp,is fun, and informative"
print(string.split(","))

Output:

['freeCodeCamp', 'is fun', ' and informative']
  1. No separator specified
string = "freeCodeCamp is fun and informative"
print(string.split())

Output:

['freeCodeCamp', 'is', 'fun', 'and', 'informative']

Note: If no separator is specified, then the string is stripped of all whitespace

string = "freeCodeCamp        is     fun and    informative"
print(string.split())

Output:

['freeCodeCamp', 'is', 'fun', 'and', 'informative']
  1. Split string using maxsplit. Here we split the string on " " twice:
string = "freeCodeCamp is fun and informative"
print(string.split(" ", 2))

Output:

['freeCodeCamp', 'is', 'fun and informative']

More Information

Check out the Python docs on string splitting