When you're working with lists in Python, sometimes you need to represent the list as a single string.
For example, this can help when you need to store a list in a database or send it over the network.
In this post, we'll learn how to take an existing list and convert it to a comma-separated string in Python.
How to convert a list to a comma-separated string in Python
To convert a list to a comma-separated string in Python, let's first start by defining a list:
PYTHONlist = ['a', 'b', 'c']
print(list)
BASH['a', 'b', 'c']
Nothing too fancy, just a list of 3 strings.
Now, to convert this list to a comma-separated string, we can use the join()
method.
This method is called on the list itself and takes a single argument: the string that will be used to join the list items.
Because we want this to be a comma-separated string, we'll pass a comma as the argument:
PYTHONlist = ['a', 'b', 'c']
print(list)
string = ",".join(list)
print(string)
BASH['a', 'b', 'c']
a,b,c
This works right away when the list items are strings.
However, when they are something else, like numbers, we'll need to convert them to strings first by wrapping them in the str()
function.
PYTHONlist = [1, 2, 3]
print(list)
string = ",".join(str(x) for x in list)
print(string)
BASH[1, 2, 3]
1,2,3
Conclusion
In this post, we learned how to convert a list to a comma-separated string in Python.
When the list items are string, we can use the join()
method directly, but when they are something else, we'll need to convert them to strings first.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Learn how to build a Slack Bot using Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript