How To Convert Python String Into List? – POFTUT

How To Convert Python String Into List?


Python string is handled as string list while interacting with characters. But one of the most used situation is how can I convert string words into python list? There are different ways to accomplish this. We will look some of them below.

String As Character List

As we stated previously strings are character list in python and most of the list functionalities can be used in these character lists. We can set range to return characters from a string. In this example we want to select first 5 character like below.

cities="Ankara Istanbul Canakkale" 
cities[0:5] 
'Ankar'
String As Character List
String As Character List

As we can see the first 5 character is returned from the string variable named cities

Words Into List With Split

Now another usage scenario is splitting words those have separated with spaces into list as elements. String variables provides some functions as helper and split is one of them. We will use split function to split string into an array.

cities="Ankara Istanbul Canakkale" 
cities.split(' ') 
['Ankara', 'Istanbul', 'Canakkale']

We provided ' ' space character as a delimiter to the split function. The city named have splitted into a list like above.

LEARN MORE  Python String Variable Type

Leave a Comment