List string Python

In this short tutorial, we look at all the different methods and the code that can be used to convert list to string in Python.

Table of Contents

  • Why convert python list to string?
  • Methods to convert python list to strings
  • Using join[]
  • Using join[] and map[]
  • Convert list to string using a loop
  • Closing thoughts and recommendations
  • Other Related Concepts

Why convert python list to string?

Converting lists to strings in python is a common practice. One of the most common use cases of converting a list to a string is to display the contents of the list as a string or to perform string manipulation.

There are multiple ways to convert list to string in python. These methods do not have any specific limitations for comparison and hence it boils down to the programmers' understanding and preference towards a particular method.

Methods to convert list to strings in python

Using join[]:

The most pythonic way of converting a list to string is by using the join[] method. The join[] method is used to facilitate this exact purpose. It takes in iterables, joins them, and returns them as a string. However, the values in the iterable should be of string data type.

In case you iterable contains int you can use the second method.

Syntax of join[]:

string.join[iterable] Here string refers to the desired separator

Parameter:


Iterable - Any iterable - list, tuples, set, etc.

Code to convert python list to string using join[]:


flexiple = ["Hire", "the", "top", "freelancers"] print[" ".join[flexiple]] #Output - "Hire the top freelancers" In the above code, the separator was a space [" "] and hence a string containing the characters in the list separated by a space is returned.

As aforementioned let us try to use join[] on an iterable containing an int. It would return a typeerror.

flexiple = ["Hire", "the", "top", 10, "python","freelancers"] print[" ".join[flexiple]] #Output - TypeError: sequence item 3: expected str instance, int found

Using join[] and map[]:

This method converts lists to strings in python using the map[] and join[] functions. This method is used when the iterable, in our case a list contains an integer value.

As the join[] methods only take in string values, we use the map[] methods to convert the integer values into a string before converting the list to a string.

The map[] methods execute a specific function for all values in an iterable. And in our case, we use it to convert each value in the list into a string.

Syntax of map[]:

map[function, iterables]
Parameter:
function - A specific function that you wish to execute
Iterable - An iterable object containing the values

By using the str[] function which converts objects to a string we can convert the int values into a string before using the join method.

Code to convert python list to string using map[]:

flexiple = ["Hire", "the", "top", 10, "python","freelancers"] print[" ".join[map[str,flexiple]]] #Output - "Hire the top 10 python freelancers"

Convert list to string in python using a loop:

The third method to convert lists to strings in python is to loop over each object and append it into a string. I would not suggest this method as python creates a new string each time you append an object. This method is slow and must only be used to help understand the concept of converting lists to strings in python. flexiple = ["Hire", "the", "top", 10, "python","freelancers"] f1 = "" for i in flexiple: f1 += str[i]+ " " print[f1] #Output = "Hire the top 10 python freelancers "

Closing thoughts and recommendations:

Converting lists to string in python would most likely not be a one-time process and the best practice would be to define a function that returns the output. And as aforementioned, there aren't significant limitations that can be used to weigh them against each other. However, they do cater to different use cases. Method 1 can be used in case you are confident that you would not be dealing with any integer values. Method 2 if you are not sure or have integer values in your list. And the last method is only for you to understand converting lists to string in python. Once you are comfortable with using them try implementing the same using list comprehension.

As part of our Flexiple tutorial series, in this article we will use two simple HTML pages. The first page will call the second page using a link and in the process using JavaScript, we will restrict the user from getting back to the first page [from the second page] using the Browser back button. 

As part of our Flexiple tutorial series, in this article we will see how to Disable or Enable Checkboxes depending upon dropdown selection using Javascript. 

There are a few useful tips to convert a Python list [or any other iterable such as a tuple] to a string for display.

First, if it is a list of strings, you may simply use join this way:

>>> mylist = ['spam', 'ham', 'eggs'] >>> print ', '.join[mylist] spam, ham, eggs

Using the same method, you might also do this:

>>> print '\n'.join[mylist] spam ham eggs

However, this simple method does not work if the list contains non-string objects, such as integers.

If you just want to obtain a comma-separated string, you may use this shortcut:

>>> list_of_ints = [80, 443, 8080, 8081] >>> print str[list_of_ints].strip['[]'] 80, 443, 8080, 8081

Or this one, if your objects contain square brackets:

>>> print str[list_of_ints][1:-1] 80, 443, 8080, 8081

Finally, you may use map[] to convert each item in the list to a string, and then join them:

>>> print ', '.join[map[str, list_of_ints]] 80, 443, 8080, 8081 >>> print '\n'.join[map[str, list_of_ints]] 80 443 8080 8081

In this tutorial, we’ll Python list to string conversion. A Python list serves the purpose of representing elements for manipulation. It basically represents a collection of homogeneous elements.

Python String also serves the purpose of the collection of elements in the form of characters as input.

The elements of the List can be converted to a String by either of the following methods:

  • By using join[] method
  • By using List Comprehension
  • Iterating using for loop
  • By using map[] method

1. Python List to String Using join[] Method

Python join[] method can be used to convert a List to String in Python.

The join[] method accepts iterables as a parameter, such as Lists, Tuples, String, etc. Further, it returns a new string that contains the elements concatenated from the iterable as an argument.

Note: The mandatory condition for join[] method is that the passed iterable should contain string elements. If the iterable contains an integer, it raises a TypeError exception.

Syntax:

Example:

inp_list = ['John', 'Bran', 'Grammy', 'Norah'] out_str = " " print["Converting list to string using join[] method:\n"] print[out_str.join[inp_list]]

In the above example, the join[] method accepts the inp_list as a parameter and concatenates the elements of the list to the out_str and thus returns a string as output.

Output:

Converting list to string using join[] method: John Bran Grammy Norah

2. List Comprehension along with the join[] method to convert Python List to String

Python List Comprehension creates a list of elements from an existing list. It further uses the for loop to traverse the items of the iterable in an element-wise pattern.

Python List Comprehension along with join[] method can be used to convert a list to a string. The list comprehension will traverse the elements element-wise and the join[] method would concatenate the elements of the list to a new string and represent it as output.

Example:

inp_list = ['John', 'Bran', 'Grammy', 'Norah'] res = ' '.join[[str[item] for item in inp_list]] print["Converting list to atring using List Comprehension:\n"] print[res]

Output:

Converting list to atring using List Comprehension: John Bran Grammy Norah

3. Python List to String conversion with map[] function

Python’s map[] function can be used to convert a list to a string.

The map[] function accepts the function and iterable objects such as lists, tuples, string, etc. Taking it ahead, the map[] function maps the elements of the iterable with the function provided.

Syntax:

Example:

inp_list = ['John', 'Bran', 'Grammy', 'Norah'] res = ' '.join[map[str, inp_list]] print["Converting list to string using map[] method:\n"] print[res]

In the above snippet of code, map[str, inp_list] function accepts str function and inp_list as arguments. It maps every element of the input iterable[ list] to the given function and returns the list of elements. Further, join[] method is used to set the output into string form.

Output:

Converting list to string using map[] method: John Bran Grammy Norah

4. Iteration using for loop to convert Python List to String

In this technique, elements of the input list are iterated one by one and are added to a new empty string. Thus, converting a list to a string.

Example:

inp_str = ['John', 'Bran', 'Grammy'] st = "" for x in inp_str: st += x print[st]

Output:

Conversion of List of characters to a string

Even a set of characters in the form of a list can be converted to a string in the same manner as above. Here is an example to demonstrate the conversion of a list of characters to a string.

Example:

inp_str = ['J', 'o', 'u', 'r', 'n', 'a', 'l', 'd', 'e', 'v'] st = "" for x in inp_str: st += x print[st]

Output:

Conclusion

Thus, in this article, we have studied the different techniques and methods of conversion of Python List to String.

References

  • StackOverflow – Conversion of List to a String in Python

Video liên quan

Chủ Đề