Python program to convert a list to string

Python program to convert a list to String :

In this example, we will learn how to convert a list to string. To achieve this, we will use join method of String. join is defined as below :

str.join(iterable)

The iterable passed to the join method should contain only string values. If it contains any non-string value, it will throw one TypeError. The value str is the separator string, i.e. the string that will be used to separate each element of the iterable. Let’s take a look into the program :

Python program :

dummy_list = ["one","two","three","four","five","six"]

separator = ' '

result_string = separator.join(dummy_list)

print(result_string)

Output :

one two three four five six

Let’s try by changing the separator to ‘,’.

dummy_list = ["one","two","three","four","five","six"]

separator = ','

result_string = separator.join(dummy_list)

print(result_string)

Output is :

one,two,three,four,five,six

Now, if we change one item of the list to int, it will produce the following output :

dummy_list = ["one",2,"three","four","five","six"]

separator = ','

result_string = separator.join(dummy_list)

print(result_string)

It will throw TypeError :

Traceback (most recent call last):
  File "test.py", line 5, in 
    result_string = separator.join(dummy_list)
TypeError: sequence item 1: expected str instance, int found

check more on python doc

Leave a Reply