By Trey Hunner
Watch as video
03:04
Let's talk about how you can convert a list into a string in Python.
Converting a list into a string with str
Let's say we have a list of strings called things
:
>>> things = ["apples", "ducks", "lemons", "cats", "potatoes"]
If we'd like to turn this list into a single string, we could pass it to the built-in str
function:
>>> str(things)
"['apples', 'ducks', 'lemons', 'cats', 'potatoes']"
But the output we get probably isn't what we were looking for.
At least not if we're trying to pass this to an end-user rather than another programmer.
So we need to ask ourselves, what are we really trying to do here?
Basically, what I'd like to do is join together each of the strings in this list by some kind of delimiter (like a space for example).
Joining a list of strings together
Many programming languages have a join
method that you can call on the list type or the array type, passing it a delimiter to join together all the strings in that list by a given delimiter.
Python doesn't have this!
>>> things.join(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
In Python, our list type does not have a join
method.
Instead, our string type has a join
method:
>>> " ".join(things)
'apples ducks lemons cats potatoes'
Here, we've asked the space character (" "
) to kindly use itself as a delimiter, joining together the items in the list of strings we've passed to it.
Concatenating a list of strings with an arbitrary delimeter
We can use any string as a delimiter.
For example, using ", "
as a delimiter would put a comma and a space between each of these strings:
>>> ", ".join(things)
'apples, ducks, lemons, cats, potatoes'
Or an empty string (""
) would put nothing between each of them, concatenating them all (smooshing them together into one long word):
>>> "".join(things)
'applesduckslemonscatspotatoes'
Python's join
method will accept any iterable of strings
Why does Python do it this way?
Why is the join
method on strings instead of the lists?
This seems kind of backwards, right?
Python does it this way for the sake of flexibility.
In Python, we have lots of types of iterables (not just lists) and we tend to think in terms of duck typing (if it looks like a duck and quacks like a duck, it's a duck).
That is, we care about the behavior (e.g. iterability) of an object instead of its type (e.g. list).
Because the join
method is on the string type, we can pass in any iterable of strings to it.
For example we can join together a tuple of strings:
>>> words = ("apple", "animal", "Australia")
>>> " ".join(words)
'apple animal Australia'
Or we can join together a file object (file objects are iterable in Python and when you loop over them you get lines):
>>> my_file = open("things.txt")
>>> "".join(my_file)
'applesnducksnlemonsncatsnpotatoesn'
We can also join together a generator object:
>>> my_file = open("things.txt")
>>> ", ".join(line.rstrip("n") for line in my_file)
'apples, ducks, lemons, cats, potatoes'
That generator expression removes new lines from the end of each line in a file and we're using the string join
method to join those lines together with a comma and a space.
Converting an iterable of non-strings into a single string
What if the iterable that we're joining together isn't an iterable of strings?
What if it's an iterable of numbers?
When we try to join together an iterable of items that aren't strings we'll get a TypeError
:
>>> numbers = [2, 1, 3, 4, 7, 11, 18]
>>> " ".join(numbers)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
Because we know that the join
method accepts any iterable of strings, we could write a generator expression that converts each of our items into a string by passing it to the built-in str
function:
>>> " ".join(str(n) for n in numbers)
'2 1 3 4 7 11 18'
So even if you're working with an iterable of non-strings, you can join them together as long as you do a little bit of pre-processing first.
Summary
If you have a list of strings in Python or any iterable of strings, and you'd like it to turn it into a single string by joining each item together with a delimiter, you can make a delimiter string, call the join
method on it, and passing in your iterable of strings.
{{ scoreMessage }}
Want to see more Python topics explained?
Hello friendly web visitor! ?
This page is part of Python Morsels, an online Python skill-building service.
The best way to learn is by doing.
In the case of Python that means writing Python code.
If you'd like to improve your Python skills every week, try out Python Morsels by entering your email below to create an account.
Python Morsels topics pages are free and the first month's worth of exercises is free as well.
You don't need to enter payment details to sign up.
You can find explanations of many other Python topics by signing up below.
By signing up, you agree to the Privacy Policy.