Friday, April 12, 2013

Python: Convert list to string and vise versa

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 its 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 its 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.

1 comment:

  1. What if the list has some str and some datetime objects?

    ReplyDelete