Pyton

Split String in Python

Split String in Python
When a string of multiple words is divided into the specific number of words based on a particular separator then it is called string splitting. Most of the programming languages use the split() method to divide a string into multiple words. The return type of this method is an array for many standard programming languages. the split() method is used in Python also to divide a string into words and it returns a list of words based on the separator. How to split() method can be used in Python is shown in this article by using different examples. Spyder3 editor is used here to write and execute the python script.

Syntax of split():

string.split(separator, maxsplit)

Here, both arguments of this method are optional. Separator works as the divider of the string and the string value breaks into smaller words based on the separator. If this argument is omitted then white space is used as default separator. maxsplit is used to define the limit of the words that will split. If this argument is omitted then the entire string will be parsed for splitting and create the list of all words based on the separator.

Example-1: Split string based on space

The following example shows the use of the split() method without any argument. Create a python file with the following script to see how it works. It will divide the text into strings based on the space and returns a tuple of the strings.

#!/usr/bin/env python3
# Define a string value
text = "Hello, Welcome to LinuxHint"
# Print message
print("The list after splitting the string:\n")
# Print the list based on white space
print(text.split())

Output:

The output is shown on the right side of the image. In the script, the variable, text contains a string of four words and the output shows a list of four items.

Example-2: Split string based on comma

You can use any character or string as the separator in the split() method. The comma(,) is used as the separator in the following example. Create a python file with the following script. A comma-separated string value will be taken as input. the split() method will create a list of strings by splitting the input value based on comma(,). Next, the values of the list will be printed using the 'for' loop.

#!/usr/bin/env python3
# Define a string of country names
country=input("Enter some names of countries with comma\n")
 
# Split the string based on comma
listCountry=country.split(',')
 
# Print message
print("\nList of countries:")
for i in range(0, len(listCountry)):
print(listCountry[i])

Output:

The output is shown on the right side of the image. The comma(,) separated country list is taken as the input value. After dividing the input based on the comma, the country name is printed in each line.

Example-3: Split string based on the specific word

Create a python file with the following script. “ and “ string is used as the separator in this example. After splitting the value of the text, the return list is stored in the variable, langval. The values of the list are printed by combining with the other string using 'for' loop.

#!/usr/bin/env python3
# Define a string value with 'and'
text = "Bash and Python and PHP"
# Split the string based on " and "
langval = text.split(" and ")
# Print the list items by combining other string
for i in range(0, len(langval)):
print("I like ", langval[i])

Output:

The output is shown on the right side of the image. 'I like ' string is added with each element of the list.

Example-4: Split string based on the limit (maxsplit)

By default, the split() method divides any text into all possible parts based on the separator value. maxsplit parameter is used in the split() method to limit the divided parts of the string. Create a Python file with the following script to know the use of maxsplit parameter of the split() method. A text value with colon(:) is assigned in the variable, person. The first time, the split() method is called with limit 3 as maxsplit value. The second time, the split() method is called with limit 2 as maxsplit value. The third time, the split() method is called with limit 1 as maxsplit value.  for loop is used to print each item of the list after calling the split() method.

#!/usr/bin/env python3
# Define a string value with ':'
person = "Jack:Manager:Bata Company:[email protected]"
print("--------Split for 3 ':'---------")
# Split the string based on ":" and limit 3
val1 = person.split(":",3)
# Print the list values
for i in range(0, len(val1)):
print("part",i+1,"-", val1[i])
print("--------Split for 2 ':'---------")
# Split the string based on ":" and limit 2
val2 = person.split(":",2)
# Print the list values
for i in range(0, len(val2)):
print("part",i+1,"-", val2[i])
print("--------Split for 1 ':'---------")
# Split the string based on ":" and limit 1
val3 = person.split(":",1)
# Print the list values
for i in range(0, len(val3)):
print("part",i+1,"-", val3[i])

Output:

The output is shown on the right side of the image. The text is divided into four parts after calling the split() for the first time because it divided the text based on 3 colons(:). The text is divided into three parts after calling the split() for the second time because it divided the text based on two colons. And the text is divided into two parts after calling the split() for the third time because it divided the text based on one colon(:).

Conclusion:

split() is a useful method for dividing any string value into multiple substrings based on the requirements. How the string values can be divided and parsed based on space, comma, colon or specific string are discussed in this article with necessary examples. I hope, you will be able to split string data in python properly after reading this tutorial.

Watch Author's Video: here

Gry Jak przechwytywać i przesyłać strumieniowo sesję gry w systemie Linux
Jak przechwytywać i przesyłać strumieniowo sesję gry w systemie Linux
W przeszłości granie w gry było uważane tylko za hobby, ale z czasem branża gier odnotowała ogromny wzrost pod względem technologii i liczby graczy. P...
Gry Najlepsze gry do grania ze śledzeniem rąk
Najlepsze gry do grania ze śledzeniem rąk
Oculus Quest niedawno wprowadził świetny pomysł śledzenia rąk bez kontrolerów. Przy stale rosnącej liczbie gier i działań, które wspierają zarówno for...
Gry Jak wyświetlić nakładkę OSD w pełnoekranowych aplikacjach i grach dla systemu Linux?
Jak wyświetlić nakładkę OSD w pełnoekranowych aplikacjach i grach dla systemu Linux?
Granie w gry pełnoekranowe lub korzystanie z aplikacji w trybie pełnoekranowym bez rozpraszania uwagi może odciąć Cię od istotnych informacji systemow...