python

How to Convert List to String in Python

In this tutorial, we are going to see how to convert list to string in Python. Python provides different types of variables for programmers. We can use data types like int, float, string, list, set… in our applications. When using different types of variables, it may be necessary to convert these to different types.
 

 

How to Convert List to String in Python using join()

Only the list containing strings can be used with the join() method. As you can see, each element is separated by a single space in the new string.

# String List
strList = ["Hi," , "welcome", "to", "StackHowTo"]
# Combine all the String of the list
str = ' '.join(strList)
# Print the list
print(str)

Output:

Hi, welcome to StackHowTo

 

Converting a list of integers into a string using join()

As mentioned before, we can convert a list consisting only of elements of type String. But what if we need to convert a list containing different data types? We will need to convert to String. For this we will use the “str” function to convert different data types to String.

# Integers List
strList = [1, 2, 3, 4, 5]  
# Combine all the String of the list
str = ' '.join(str(elem) for elem in strList) 
# Print the list
print(str)

Output:

1 2 3 4 5
 

Specify different delimiters

So far we have used space as a separator between elements. But we can specify different delimiters by changing the space with a new delimiter.

# String List
strList = ["Hi," , "welcome", "to", "StackHowTo", 1, 2, 3, 4]
# Combine all the String of the list
str = '_'.join([str(elem) for elem in strList ])
# Print the list
print(str)

Output:

Hi,_welcome_to_StackHowTo_1_2_3_4
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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