Python List To String

python-list-to-string-ipcisco.com-2

In python, we use Python List To String convertion for various purposes. In this lesson, we will learn this List To String convertion. Here, we will use python join () function.

 

Let’s do a python list example and learn how to convert Python List To String with the help of python join() function. Here, we will create a list with three members and then we will print these members with spaec character between list members.

 


You can also learn how to Sort a Python list


 

animals = ['Cats', 'Dogs', 'Birds']
string1 = ' '.join(animals)
print(string1)

 

The output of this python string list code will be like below. The string list members are converted to a string with a space between each word. Above, in the second code line, we have mentioned this space between quotations as seperator.

 

Cats Dogs Birds

 


You can also check Python List Methods


python-list-to-string-ipcisco.com-1

 

We can also change this seperator with other signs. For our list example, let’s use dash (-) this time.

 

animals = ['Cats', 'Dogs', 'Birds']
string1 = '-'.join(animals)
print(string1)

 

The output of this code will be:

 

Cats-Dogs-Birds

 

python-list-to-string-ipcisco.com-2

 

Now, we will do the same example with a number string list. We will change this number string lists to one string. There will be dash (-) between each word. Here each member of the list is string, even if they seem like numbers.

 

animals = ["1","2","3","4"]
string1 = ' '.join(animals)
print(string1)

 

The output of this python list code will be like below as “1 2 3 4“.

 

1 2 3 4

 

how to-convert-list-to-string-python-ipcisco

 

As you can see above, the members of the list is printed with a space between each member. We have use space as seperator here. Instead of space, we can use any other charaters.

 

In this python string list lesson, we have learned how to convert a list to a string. In other words, we have learned how to convert Python List To String. This is one of the used functions for converting in python coding for various purposes. To learn better, you should practice more with different examples.

 

Back to: Python Programming Course > Python Lists

Leave a Reply

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

Python Programming Course

Collapse
Expand