How do you convert a list to a string in Python?

You can use the join() method to convert a list into a string. This method, belonging to strings, joins the elements of a list together with a specified character and returns a string.

Here’s an example of converting a list containing numbers into a comma-separated string:

numbers = [1, 2, 3, 4, 5]
string = ','.join(str(n) for n in numbers)
print(string)  # 输出: "1,2,3,4,5"

In the example above, we used a generator expression to convert each element in the list into a string. We then used the join() method to combine these strings together, specifying a comma as the separator. The end result is a string separated by commas.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds