Python String Split

python-string-split-ipcisco

In this lesson, we will focus on Python String Split. How can we use Python String Split in Python coding? We use this method we can divide the string according to a given seperator and returns with a list of words or strings that are build from the original string. Split function uses a parameter named str. This str parameter is used to mention the seperator parameter.

 

For example, let’s check the below python code for Python String Split. In this code, there is a variable named cities and it has a string value consist of different cities. All these cities are seperated with a comma (,).

 

cities = "Istanbul,Paris,Amsterdam,Barcelona, New York"
print(cities.split(','))

 

The output of this python code will be like below:

 

['Istanbul', 'Paris', 'Amsterdam', 'Barcelona', 'New York']

 

python-string-split-ipcisco

 

As you can see above, we use split() function with comma (,) operator. Here, this operatior is our seperator and according to it, we divide our main string into a list consist of smaller strings. In other words, we divide the cities string into separate city strings.

 

We can use different operators as string seperator. For example, below, we use dash (-) as seperator.

 

countries = "United Kingdom-Italy-India-Saudi Arabia-Brazil-France"
print(countries.split('-'))

 

The output of this Python String Split code will be again a list like below:

 

['United Kingdom', 'Italy', 'India', 'Saudi Arabia', 'Brazil', 'France']

 

string-split-in-python-ipcisco

 

By the way, if we do not use str parameter of split function, this function uses space as seperator by default. For example if your string is a sentence, split function divides each words as a new string in the list.

 

message = 'life is good'
print(message.split())

 

The output of this Python String Split code will give the list of the words in this sentence.

 

['life', 'is', 'good']

 

In this lesson, we have learned Python String Split. We have seen how to divide a string and create a string list from old string.

 

Back to: Python Programming Course > Python Strings

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact

  • info@ipcisco.com
IPCisco is the Winner! “Best Certification Study Journey of 2019!”

Cisco-ITBlogAwards-2019-Winner-IPCisco-k

Python Programming Course