How to join a list with prefix in python

Sometimes you may need to turn your list into a string and the most pythonic way of doing is by using join.
But when it comes to adding a prefix with the list its does not work properly lets give a try.

>>> animals = ['Cat', 'Dog', 'Elephant']
>>> "The".join(animals)

What that's not prefix at all but that can be fixed by adding just "\n" with prefix.
Lets try.

>>> print("\nThe ".join(animals))
The Dog
The Elephant

Ok, that seems to work but if we look at the output we are missing the prefix with first output.
so how to fix that?

Well a simple way is to map all the input with prefix and convert that into string.
Lets Try.

>>> print("\n".join(map(lambda x: "The " + x, animals)))
The Cat
The Dog
The Elephant

and perfect it works.

some people prefer to use list comprehension over map and filter, so we can

>>> print("\n".join(["The " + x for x in animals]))
The Cat
The Dog
The Elephant

Note : you will have to convert list into string if the list is having data other then string

For Example:
>>> print("\n".join(map(lambda x: "prefix" + str(x), some_list)))

No comments :

Post a Comment