Scripting

Python split() Function

Python split Function

Introduction

The split() function is used to split a string and print out a list containing the words in that string. You can specify a separator between words in a string for the function to recognize.

In a short string, this command is very useful to split words and make it easier to parse the string. And the article below, we will show you how to use the split() function in Python through several examples as go through below.

Example

str = "Welcome to my company"

x = str.split()

print(x)

Output:
[‘Welcome’, ‘to’, ‘my’, ‘company’]

Definition

The split() function will split a string into a list of words contained in the string.

You must specify a separator between words in a string for the function to recognize, the default is a space.

The syntax

string.split(separator, maxsplit)

Parameter Values:

separator: delimiter

maxsplit: number of parts you want to split

More example

Example 1: separated by “,”

str = "Hello, my name is Linda, I'm 20 years old"

x = str.split(", ")

print(x)

Output:

[‘Hello’, ‘my name is Linda’, “I’m 20 years old”]

Example 2: separated by “#”

str = "Hello#my name is Linda#I'm 20 years old"

x = str.split("#")

print(x)

Output:

[‘Hello’, ‘my name is Linda’, “I’m 20 years old”]

Example 3: split into 2 parts

str = "Hello#my name is Linda#I'm 20 years old"

x = str.split("#", 1)

print(x)

Output:

[‘Hello’, “my name is Linda#I’m 20 years old”]

Conclusion

Hope you understand our tutorial on how to use the split() function in Python.

Thanks for reading!

Similar Posts