Python Program to Convert a List to a String
Beginner · Lists
This program turns a list into a single string with the join() method, which puts a separator of your choice between the items. It also shows why str() is usually not what you want, and how to join a list of numbers.
Program
list_to_string.py
words = ["Python", "is", "fun"] # or: words = input("Enter some words: ").split()
print("List:", words)
print("Joined with spaces:", " ".join(words))
print("Joined with commas:", ", ".join(words))
print("Joined with nothing:", "".join(words))
print("str() keeps the brackets:", str(words))
# join() only accepts strings, so turn the numbers into strings first
numbers = [10, 20, 30]
number_strings = []
for n in numbers:
number_strings.append(str(n))
print("Numbers joined with dashes:", "-".join(number_strings))
Output
List: ['Python', 'is', 'fun'] Joined with spaces: Python is fun Joined with commas: Python, is, fun Joined with nothing: Pythonisfun str() keeps the brackets: ['Python', 'is', 'fun'] Numbers joined with dashes: 10-20-30
How it works
" ".join(words)reads as "join the words with a space between them". The separator is the string before the dot.- Any string can be the separator, including
", "or the empty string"". str(words)gives the list exactly as Python prints it, with brackets and quotes, which is rarely what you want.join()raises aTypeErrorif any item is not a string, so the numbers are converted withstr()first.
Other ways to write it
Using a loop instead of join()
Using a loop instead of join()
words = ["Python", "is", "fun"]
sentence = ""
for i in range(len(words)):
sentence += words[i]
if i < len(words) - 1: # no space after the last word
sentence += " "
print("Sentence:", sentence)
Output
Sentence: Python is fun
Building the string by hand shows what join() does for you, including leaving out the separator after the last item.
Using map() for numbers
Using map() for numbers
numbers = [10, 20, 30]
print("With map():", ", ".join(map(str, numbers)))
letters = ["P", "y", "t", "h", "o", "n"]
print("Letters to a word:", "".join(letters))
Output
With map(): 10, 20, 30 Letters to a word: Python
map(str, numbers) turns every number into a string in one step, which is the shortest way to join numbers.
Try it yourself
Join the list ["2026", "01", "15"] with "/" to print a date.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Split a String into a List
- Reverse the Words in a Sentence
- Make an Acronym from a Phrase
- Capitalize the First Letter of Each Word
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises