How to Convert a List to a String in Python? | 1
|

How to Convert a List to a String in Python?

Most newbies to Python find this fascinating. Converting a list of elements to a long string requires only one line of code.

Here’s an example.

Suppose we have a list of names, and we need to convert it into a string. We also want each element separated by a comma. The following code will do the trick.

l = ['apple', 'orange', 'mango']

# This is where we join the elements 
text = ",".join(l)

print(text)

>>> ' apple,orange,mango'
JavaScript

In the above example, we use the join method of any string to convert a list. Instead of a comma, we can give any text. As we change it, you’ll notice that the connecting part between any two-element is different. Instead of a comma, we can provide any text.

l = ['apple', 'orange', 'mango']

text = "-".join(l)
print(text)
>>> ' apple-orange-mango'

text = "-***-".join(l)
print(text)
>>> ' apple-***-orange-***-mango'
JavaScript

Related:How to Find the Index of an Element in a List in Python?

Converting a list of numbers to a string

The join method works fine for a list of strings. Yet, if the list comprises numbers, it throws an error.

l = [1,2,3]
",".join(l)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
JavaScript

Another little Python trick in such a situation is to use comprehension. Comprehensions are a convenient way to loop through elements without writing multi-line statements.

 

Here, in the following example, we convert each element in the list to a string and then use the join method as before. We can see the list is now converting to text without any error.

l = [1,2,3]

# Using the list comprehension
text =",".join(str(el) for el in l)

print(text)
>>> '1,2,3'
JavaScript

Conditionally select elements before joining.

Often we don’t want to join every element of a list. We may wish to select a few based on some conditions. We can extend the list comprehension to include such situations to tackle this.

Suppose, in addition to converting numbers to strings, we might want to include only odd numbers in our join operation. The following code will do it.

l = [1,2,3,4,5,6,7]

# Using the list comprehension with a filter for odd numbers. 
text =",".join(str(el) for el in l if el%2==1)

print(text)
>>> '1,3,5,7'
JavaScript

In the above example, we used the el%2==1 condition to include only elements that meet this condition. That is to have only odd numbers.

Related: How to Create Interactive CLIs in Python?

Transform list elements and join them to create a string.

We need to apply some complex transformations to the elements in some instances before joining them. The change could be anything.

The following list has both strings and numbers in the list in the following example. We need to use the texts as it is. But for numbers, without directly converting them into a string, we need to use it’s literal. We do it by looking it up into a dictionary.

Let’s create a small function that does the lookup.

def number_lookup(n:[int,str])->str:

  # lookup number
  if type(n) == int:
    d = {
      1:'one',
      2:'two', 
      3:'three',
      4:'four',
      5:'five', 
      6:'six', 
      7:'sever', 
      8:'eight',
      9:'nine',
      10:'ten'
    }

    return d[n]
  
  # return string as it is
  return n
JavaScript

We can use this function to convert the elements as we did with str. But there’s a better method to do this. Use map functions when you have complex logic to apply to a list.

l = [1, "two", 3, 4, "five", 6, 7]

text = ",".join(map(number_lookup, l))

print(text)
>>> one,two,three,four,five,six,sever
JavaScript

In the above example, we used the map function to apply the number_lookup to our list before joining them. When the transformation is complex, it’s always better to use the map function instead of list comprehension.


Thanks for the read, friend. It seems you and I have lots of common interests. Say Hi to me on LinkedIn, Twitter, and Medium. I’ll break the ice for you.

Not a Medium member yet? Please use this link to become a member because I earn a commission for referring at no extra cost for you.

Similar Posts