How to convert python list to string

1 year ago Lalit Bhagtani 0

In this tutorial, we will learn about converting python list object to string.

Python List To String

We can use String’s join method for converting List object to String.

Syntax : < String Object >.join(< Iterable Object >)

This method returns a string, which is a concatenation of all the strings in a list. The separator between the elements of the list is a string object on which join method is called. An Exception ( Type Error ) will be raised, if list contains any non-string element.

Example:

[datacamp_exercise lang=”python” height=”400″ min-height=”300″ max-height=”500″]
[datacamp_pre_exercise_code]

[/datacamp_pre_exercise_code]
[datacamp_sample_code]
# create list object and assign it to variable l
l = [‘1′,’2′,’3′,’4′,’5’]

# create single space string and assign it to variable separator
separator = ‘ ‘

# call join() method on separator by passing list l as an argument
output = separator.join(l)

# print the value of variable output
print(output)

# second example with ‘-‘ as a separator
separator = ‘-‘

output = separator.join(l)

print(output)
[/datacamp_sample_code]
[datacamp_solution]

[/datacamp_solution]
[/datacamp_exercise]

References :-

  1. String Join Method Docs

You can also check :- 

  1. Python List
  2. Python String

That’s all for How to convert python list to string, you can learn more about tuple . If you liked it, please share your thoughts in comments section and share it with others too.