Given a list, write a Python program to convert the given list to string. There are various situations we might encounter when a list is given and we convert it to string. For example, conversion to string from the list of string or the list of integer. Show Example: Input: ['Geeks', 'for', 'Geeks'] Output: Geeks for Geeks Input: ['I', 'want', 4, 'apples', 'and', 18, 'bananas'] Output: I want 4 apples and 18 bananas Let’s see various ways we can convert the list to string. Method #1: Iterate through the list and keep adding the element for every index in some empty string. Python3
Method #2: Using .join() method Python3
But what if the list contains both string and integer as its element. In those cases, above code won’t work. We need to convert it to string while adding to string. Method #3: Using list comprehension Python3
Output: I want 4 apples and 18 bananas Method #4: Using map() Use map() method for mapping str (for converting elements in list to string) with given iterator, the list. Python3
Output: I want 4 apples and 18 bananas Method #5: Using enumerate function Python3
Output I want 4 apples and 18 bananas Method #6: Using in operator Python3
How can I convert a list to a string using Python?
Aran-Fey 36.4k10 gold badges96 silver badges141 bronze badges asked Apr 11, 2011 at 8:51
3
Use
If the list contains integers, convert the elements to string before joining them:
Mateen Ulhaq 22.2k16 gold badges86 silver badges127 bronze badges answered Apr 11, 2011 at 8:52
Senthil KumaranSenthil Kumaran 52.3k14 gold badges90 silver badges127 bronze badges 7
Mateen Ulhaq 22.2k16 gold badges86 silver badges127 bronze badges answered Apr 11, 2011 at 8:53
Andrey SboevAndrey Sboev 7,3241 gold badge19 silver badges35 bronze badges 2
Mateen Ulhaq 22.2k16 gold badges86 silver badges127 bronze badges answered Apr 11, 2011 at 8:56
NathanNathan 5,98510 gold badges44 silver badges54 bronze badges 4 How do you convert a list in Python?Typecasting to list can be done by simply using list(set_name) . Using sorted() function will convert the set into list in a defined order. The only drawback of this method is that the elements of the set need to be sortable.
How do I print a list like a string in Python?Convert a list to a string for display : If it is a list of strings we can simply join them using join() function, but if the list contains integers then convert it into string and then use join() function to join them to a string and print the string.
How do I convert a list to multiple strings in Python?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.
How do you extract a string from a list in Python?Calling str on each element e of the list l will turn the Unicode string into a raw string. Next, calling tuple on the result of the list comprehension will replace the square brackets with parentheses.
|