Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (6.1k points)
Actually, I am very new to python. So could you please help me out with this question?

1 Answer

0 votes
by (11.7k points)

We can easily convert the list into a string in Python using various methods. Some of the easy methods are listed down below.

1) Using Iterations(loops)

Code:

x_list = ["There", "are", 5, "cars"] 

result = "" 

for elements in x_list: 

    result += str(elements) + " " 

print(result)

Explanation: 

a)Above code says that a simple list is created. An empty string is created as-  result=""

b)This empty string is used to add the elements of every index during an iteration of the list.

c)Now the traversing of the srting is done in the line down below.

for elements in x_list: 

    result += str(elements) + " "

d) Hence the list is converted into a string and gets stored in the result string.

print(result)

2) Using .join() Method

Code:

x_list = ["He", "has", 3, "chocolates"] 

result = ' '.join(str(i)

 for i in x_list) 

print(result)

Explanation: 

a) A simple list is created and stored in x_list

b) Now the list is iterated using for loop and the iterated list is stored in an empty result string.

result = ' '.join(str(i) for i in x_list) 

c) Hence we get the list converted into a string.

print(result)

Browse Categories

...