How to turn a list into string

Here is a quote from python.org describing how we can use the join method.

str.join(iterable)

Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.

As it can be seen it isn’t only for strings but for something called “iterable”. Again when we look at python.org what this iterable means;

iterable

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict and file and objects of any classes you define with an __iter__() or __getitem__() method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...)....

So it means we can use list, tuples all sequence types. This means I can use it to turn a list into a string which is very handy when I read files via python. For example;

>>> ":".join(a)
'root:/bin/bash:password'

Bingo, we have a string out of a list!

About: rtoodtoo

Worked for more than 10 years as a Network/Support Engineer and also interested in Python, Linux, Security and SD-WAN, currently living in the Netherlands and works as a Network Support Engineer. // JNCIE-SEC #223 / RHCE / PCNSE


You have a feedback?

This site uses Akismet to reduce spam. Learn how your comment data is processed.