Python tips - How to easily convert a list to a string for display

There are a few useful tips to convert a Python list (or any other iterable such as a tuple) to a string for display.

First, if it is a list of strings, you may simply use join this way:

>>> mylist = ['spam', 'ham', 'eggs']
>>> print ', '.join(mylist)
spam, ham, eggs

Using the same method, you might also do this:

>>> print '\n'.join(mylist)
spam
ham
eggs

However, this simple method does not work if the list contains non-string objects, such as integers.

If you just want to obtain a comma-separated string, you may use this shortcut:

>>> list_of_ints = [80, 443, 8080, 8081]
>>> print str(list_of_ints).strip('[]')
80, 443, 8080, 8081

Or this one, if your objects contain square brackets:

>>> print str(list_of_ints)[1:-1]
80, 443, 8080, 8081

Finally, you may use map() to convert each item in the list to a string, and then join them:

>>> print ', '.join(map(str, list_of_ints))
80, 443, 8080, 8081
>>> print '\n'.join(map(str, list_of_ints))
80
443
8080
8081

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

if list contains integer

if list contains integer values, error will occur. therefore first need to convert them all into string
example
int_arr = range[10]
convert_first_to_generator = (str(w) for w in int_arr)
print ''.join(convert_first_to_generator)

Thnx so much.your

Thnx so much.your explaination was very useful.
i appreciate that.

Good

Simple yet Effective

Thanks! Helped me solve my

Thanks! Helped me solve my problem. :)