Single element list to string python

While working with python data types, there are situations when you want to convert the data collected from one type to another. There are 4 methods by which we can convert a list to a string in python with fewer lines of code. These methods of converting a list into a string include iteration, comprehension, join[], and map[] method. But before understanding all these conversion methods in detail, let us understand what are lists and strings.

What is a List? 

The list is one of the most important data types in the python language. A python list is an ordered and changeable collection of data objects. In Python language, the list is written as commas separated values inside the square bracket. It can also contain duplicate elements along with the negative indexing elements. The important advantage of the list is that the elements inside the list are not compulsory to be of the same data type. List undergo the operations like slicing, concentrating, etc., just like the string operations. Also, you can create a nested list, i.e., a list containing another list.

Example

sam_list = [10,"favtutor",["compile","it"]] print[sam_list]

Output:

[10, 'favtutor', ['compile', 'it']]

 

What is a String?

A string is defined as a sequence of characters where a character is a simple symbol. For example, in the English Language, we have 26 characters available. The computer system does not understand characters therefore, it deals with binary numbers. Even though we can see characters on our monitor screens, internally it is stored and manipulated internally as a combination of 0's and 1's. In the Python programming language, a string is a sequence of Unicode characters. It s an immutable sequence data type wrapped inside single or double-quotes. That means that once you define a string, you cannot change it.

You can also assign a multi-line string to a variable using triple quotes. Many string manipulation methods are available for string data types like join[], split[], concatenation, etc. However, this method does not modify the original strings but creates a copy and modifies them accordingly.

Example

a = "Compile With Favtutor" print[a]

Output

Convert List to String in Python

As mentioned earlier, there are 4 methods to convert a list to string in python. Let us study them one by one in detail, along with the example and corresponding output. 

1] Iterating through the List

This method will iterate every index of the input list one by one and add it to the empty string. 

Example

# converting list to string using iteration def listToString[s]: # initialize an empty string string = "" # traverse in the string for element in s: string += element # return string return string # Driver code s = ['Compile ', 'With ', 'Favtutor '] print[listToString[s]]

Output:

 

2] Using join[] method

Every element of the list will be traversed and added to the empty string. Join[] method is used to concatenate all these elements and form the final output. This method will fail to work if the list contains integer elements, and therefore the output will be TypeError Exception

Example

# converting list to string using join[] method # Function to convert def listToString[s]: # initialize an empty string string = " " # return string return [string.join[s]] # Driver code s = ['Compile ', 'With ', 'Favtutor'] print[listToString[s]]

Output:

 

3] Using List Comprehension

As mentioned earlier, the join[] method will fail to work if you have integer elements in your input list. But to overcome this failure, you can use the List comprehension along with join[] method. List comprehension will help you to create a list of elements from the existing input list. And later uses a for loop to traverse the elements by element-wise patterns. After the traversal of elements by list comprehension, you can use the join[] method to concatenate the traversed elements of the list into an empty string. 

Example

# converting list to string using list comprehension s = ['Compile', 'With', 'Favtutor'] # using list comprehension listToStr = ' '.join[[str[element] for element in s]] print[listToStr]

Output:

 

4] Using map[] function

map[] function accepts the iterable objects such as tuples, lists, or strings. Hence, it is used to map the elements of the iterable objects with the function provided. 

Example

# converting list to string using map[] function s = ['Compile', 'With', 'Favtutor'] # using list comprehension listToStr = ' '.join[map[str, s]] print[listToStr]

Output:

Conclusion

List and string have their own importance as a data type in python. This article referred to python lists and strings in detail, along with different techniques and methods to convert list data types into strings. It is highly recommended to learn and understand all these methods in detail as they are very effective and efficient for converting the list to string using fewer lines of code. 

In this tutorial, we’ll look at how to convert a python list to a string.

How to convert a python list to a string?

You can use the string join[] function in a list comprehension to easily create a string from the elements of the list. The following is the syntax:

s = ''.join[str[i] for i in ls]

Here, we iterate through the elements of the list ls converting each to a string object using list comprehension and then join the elements into a string using the string join[] method. For more details on the join[] method, refer to this guide.

Examples

Let’s look at a few examples.

1. List of string to string

To get a single string from a list of strings, you can use the syntax above. But, since all the items in the list are already string, you don’t need to explicitly convert them into a string. See the example below.

ls = ['a', 'e', 'i', 'o', 'u'] s = ''.join[ls] print[s]

Output:

aeiou

In the above example, you can see that we directly passed the list to the join[] function without converting each item to string. This was possible because the items in the list were already string.

2. List of integers to string

To get a string from a list of integers, you need to explicitly convert each list item to a string [for example, in a list comprehension] before applying the join[] function. See the example below.

ls = [1, 2, 3, 4] s = ''.join[str[i] for i in ls] print[s] print[type[s]]

Output:

1234

In the above example, the string s is created from the items of the list ls containing integer items.

If you’re not sure about the types of items in the list, it’s better to convert them to string and then pass it to the join[] function which is used to join string objects.

3. List to string with each item on newline

You can use a custom string to join the items in the list. The above examples used an empty string to join the items but you use any other string like a whitespace ' ', newline character '\n', etc as well. See the example below.

ls = [1, 2, 3, 4] s = '\n'.join[str[i] for i in ls] print[s]

Output:

1 2 3 4

Here, we use a newline character '\n' to join the list. The resulting string has each item of the list separated by a newline character.

For more on the python string join[] function, refer to the python docs.


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Video liên quan

Chủ Đề