Categories
coding Python

How to convert a Python list into a string in a strange way

Given a list in Python, suppose you wanted a string representation of that list. Easy enough:


str( [ 1, 2, 3 ] )

However, suppose you did not want the standard notation, but rather apply some function to each string element or simply do away with the brackets and commas, you can use list comprehension, the join function and an empty string literal:


''.join( str( i ) for i in [ 1, 2, 3 ] )

I already knew list comprehension, but using it in this scenario and with a string literal as an object was new to me. Anyway, using such code is probably a bad idea, since it might be hard to read! At the very least, one should stow it away in a function with a fitting name, such as jointStringRepresentationOfListItems( list ). But really, I am not even sure what I would use that for…

Update: even better is this:


','.join( map( str, [ 1, 2, 3 ] ) )

Leave a Reply

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