Python have many data types such as string, Boolean, number, list, tipple, dictionary etc. We can not club a data type with other data type, if you do so we get errors. Suppose take lists and string data type and try to combine both, as the data types are different Python will not allow you to do so. If we do that it will get an error as shown below.

TypeError: can only concatenate list (not “str”) to list

But some times it’s required to combine these two types, what is the solution?

The solution is to convert one data type to other before doing a combination.

How to convert a list data type to string data type in Python?

 Use inbuilt python function join to convert a list to a string

Syntax for join function:

separator.join(sequence)

“separator” from above can be any character you specify to separate the sequence of strings variable in join function “sequence”

Join function examples:

I have a following list

list1 = [“surendra”, “is”, “a”, “good”, “programmer”]

and string to separate above list once it’s converted to string is ‘-‘. Now joining above list using join function:

Str1 = ‘-‘.join(list1)

print Str1

Output:

surendra-is-a-good-programmer

You can change the separator what ever you want, even a group of chars as well.

How to convert a string data type to list data type in Python?

Use inbuilt python function “split”

Syntax for split function:

string.split(‘seperator’)

“string” in the above syntax is a string which you want to split using split function and “separator” in the split function is to separate the list elements.

Example:

Str1=’surendra-is-a-good-programmer’
list1 = Str1.split(‘-‘)
print list1

Output:

[‘surendra’, ‘is’, ‘a’, ‘good’, ‘programmer’]

Hope it helps you people. Please share your thoughts on this.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.