Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python List to String: A Helpful Guide with Interactive Shell

#1
Python List to String: A Helpful Guide with Interactive Shell



Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list?

Example: You want to convert list ['learn ', 'python ', 'fast'] to the string 'learn python fast'.

Solution: to convert a list of strings to a string, do the following.

  • Call the ''.join(list) method on the empty string '' that glues together all strings in the list and returns a new string.
  • The string on which you call the join method is used as a delimiter between the list elements.
  • If you don’t need a delimiter, just use the empty string ''.

Code: Let’s have a look at the code.

lst = ['learn ', 'python ', 'fast']
print(''.join(lst))

The output is:

learn python fast

Try it yourself in our interactive Python shell:

You can also use another delimiter string, for example, the comma:

lst = ['learn' , 'python', 'fast']
print(','.join(lst))
# learn,python,fast

What Are Alternative Methods to Convert a List of Strings to a String?


Python is flexible—you can use multiple methods to achieve the same thing. So what are the different methods to convert a list to a string?

  • Method 1: Use the method ''.join(list) to concatenate all strings in a given list to a single list. The string on which you call the method is the delimiter between the list elements.
  • Method 2: Start with an empty string variable. Use a simple for loop to iterate over all elements in the list and add the current element to the string variable.
  • Method 3: Use list comprehension [str(x) for x in list] if the list contains elements of different types to convert all elements to the string data type. Combine them using the ''.join(newlist) method.
  • Method 4: Use the map function map(str, list] if the list contains elements of different types to convert all elements to the string data type. Combine them using the ''.join(newlist) method.

Here are all four variants in some code:

lst = ['learn' , 'python', 'fast'] # Method 1
print(''.join(lst))
# learnpythonfast # Method 2
s = ''
for st in lst: s += st
print(s)
# learnpythonfast # Method 3
lst = ['learn', 9, 'python', 9, 'fast']
s = ''.join([str(x) for x in lst])
print(s)
# learn9python9fast # Method 4
lst = ['learn', 9, 'python', 9, 'fast']
s = ''.join(map(str, lst))
print(s)
# learn9python9fast

Again, try to modify the delimiter string yourself using our interactive code shell:

So far so good. You’ve learned how to convert a list to a string. But that’s not all! Let’s dive into some more specifics of converting a list to a string.

Python List to String with Commas


Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a comma as the delimiter between the list elements?

Example: You want to convert list ['learn', 'python', 'fast'] to the string 'learn,python,fast'.

Solution: to convert a list of strings to a string, call the ','.join(list) method on the delimiter string ',' that glues together all strings in the list and returns a new string.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print(','.join(lst))

The output is:

learn,python,fast

Python List to String with Spaces


Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a space as the delimiter between the list elements?

Example: You want to convert list ['learn', 'python', 'fast'] to the string 'learn python fast'. (Note the empty spaces between the terms.)

Solution: to convert a list of strings to a string, call the ' '.join(list) method on the string ' ' (space character) that glues together all strings in the list and returns a new string.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print(' '.join(lst))

The output is:

learn python fast

Python List to String with Newlines


Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a newline character as the delimiter between the list elements?

Example: You want to convert list ['learn', 'python', 'fast'] to the string 'learn\npython\nfast' or as a multiline string:

'''learn
python
fast'''

Solution: to convert a list of strings to a string, call the '\n'.join(list) method on the newline character '\n' that glues together all strings in the list and returns a new string.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print('\n'.join(lst))

The output is:

learn
python
fast

Python List to String with Quotes


Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a comma character followed by an empty space as the delimiter between the list elements? Additionally, you want to wrap each string in double quotes.

Example: You want to convert list ['learn', 'python', 'fast'] to the string '"learn", "python", "fast"' :

Solution: to convert a list of strings to a string, call the ', '.join('"' + x + '"' for x in lst) method on the delimiter string ', ' that glues together all strings in the list and returns a new string. You use a generator expression to modify each element of the original element so that it is enclosed by the double quote " chararacter.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print(', '.join('"' + x + '"' for x in lst))

The output is:

"learn", "python", "fast"

Python List to String with Brackets


Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list—using a comma character followed by an empty space as the delimiter between the list elements? Additionally, you want to wrap the whole string in a square bracket to indicate that’s a list.

Example: You want to convert list ['learn', 'python', 'fast'] to the string '[learn, python, fast]' :

Solution: to convert a list of strings to a string, call the '[' + ', '.join(lst) + ']' method on the delimiter string ', ' that glues together all strings in the list and returns a new string.

Code: Let’s have a look at the code.

lst = ['learn', 'python', 'fast']
print('[' + ', '.join(lst) + ']')

The output is:

[learn, python, fast]

Python List to String and Back


Problem: You want to convert a list into a string and back to a list.

Example: Convert the list ['learn', 'python', 'fast'] to a string "['learn', 'python', 'fast']" and back to a list ['learn', 'python', 'fast'].

Solution: Use the following two steps to convert back and forth between a string and a list:

  • Use the built-in str() function to convert from a list to a string.
  • Use the built-in eval() function to convert from a string to a list.
lst = ['learn', 'python', 'fast'] converted = str(lst)
print(converted)
# ['learn', 'python', 'fast']
print(type(converted))
# <class 'str'> original = eval(converted)
print(original)
# ['learn', 'python', 'fast']
print(type(original))
# <class 'list'>

Although the output of both the converted list and the original list look the same, you can see that the data type is string for the former and list for the latter.

Convert List of Int to String


Problem: You want to convert a list into a string but the list contains integer values.

Example: Convert the list [1, 2, 3] to a string '123'.

Solution: Use the join method in combination with a generator expression to convert the list of integers to a single string value:

lst = [1, 2, 3]
print(''.join(str(x) for x in lst))
# 123

The generator expression converts each element in the list to a string. You can then combine the string elements using the join method of the string object.

If you miss the conversion from integer to string, you get the following TypeError:

lst = [1, 2, 3]
print(''.join(lst)) '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> print(''.join(lst))
TypeError: sequence item 0: expected str instance, int found '''

Python List to String One Line


To convert a list to a string in one line, use either of the three methods:

  • Use the ''.join(list) method to glue together all list elements to a single string.
  • Use the list comprehension method [str(x) for x in lst] to convert all list elements to type string.
  • Use str(list) to convert the list to a string representation.

Here are three examples:

lst = ['finxter', 'is', 'awesome']
print(' '.join(lst))
# finxter is awesome lst = [1, 2, 3]
print([str(x) for x in lst])
# ['1', '2', '3'] print(str(lst))
# [1, 2, 3]

Where to Go From Here


Want to increase your Python skill on a daily basis? Just by following a series of FREE Python course emails? Then join the #1 Python Email Academy in the world!

For my subscribers, I regularly publish educative emails about the most important Python topics. Register and join my community of thousands of ambitious coders. I guarantee, you will love it!

(Besides—it’s free and you can unsubscribe anytime so you’ve nothing to lose and everything to gain.)

join the #1 Python Email Academy in the world!



https://www.sickgaming.net/blog/2020/04/...ive-shell/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python abs() Function xSicKxBot 0 4 6 hours ago
Last Post: xSicKxBot
  [Tut] Python Built-In Functions xSicKxBot 0 6 Yesterday, 08:02 AM
Last Post: xSicKxBot
  [Tut] Show Don’t Tell: Commenting Python Best Practices xSicKxBot 0 4 11-27-2020, 03:41 AM
Last Post: xSicKxBot
  [Tut] Matplotlib Scatter Plot – Simple Illustrated Guide xSicKxBot 0 7 11-25-2020, 01:23 AM
Last Post: xSicKxBot
  [Tut] How to Catch and Print Exception Messages in Python xSicKxBot 0 7 11-23-2020, 11:45 PM
Last Post: xSicKxBot
  [Tut] Python next() xSicKxBot 0 8 11-22-2020, 08:17 AM
Last Post: xSicKxBot
  [Tut] Python Math Domain Error (How to Fix This Stupid Bug) xSicKxBot 0 11 11-21-2020, 08:01 AM
Last Post: xSicKxBot
  [Tut] Python Int to String with Leading Zeros xSicKxBot 0 18 11-17-2020, 03:22 AM
Last Post: xSicKxBot
  [Tut] Python Function Call Inside List Comprehension xSicKxBot 0 25 11-16-2020, 02:42 AM
Last Post: xSicKxBot
  [Tut] [Ultimate Guide] Freelancing as a Data Scientist xSicKxBot 0 26 11-15-2020, 02:12 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
News - Nintendo Shares Tips On How To Ke...
Last Post: xSicKxBot
Today 02:43 PM
» Replies: 0
» Views: 1
News - Random: Amateur Dev Releases Reim...
Last Post: xSicKxBot
Today 02:43 PM
» Replies: 0
» Views: 1
[Tut] Python abs() Function
Last Post: xSicKxBot
Today 09:45 AM
» Replies: 0
» Views: 4
News - It Looks Like Kadabra Can Finally...
Last Post: xSicKxBot
Today 07:46 AM
» Replies: 0
» Views: 7
News - Bungie Cancels Destiny 2's Trials...
Last Post: xSicKxBot
Today 07:46 AM
» Replies: 0
» Views: 5
(Indie Deal) ?U+Me Black Friday Adult Bu...
Last Post: xSicKxBot
Today 06:42 AM
» Replies: 0
» Views: 4
[1.06] BO4 Zombie Trainer (Call of duty ...
Last Post: theolikeappels
Today 01:00 AM
» Replies: 31
» Views: 1188
Blender 2.91 Released
Last Post: xSicKxBot
Today 12:49 AM
» Replies: 0
» Views: 4
News - Feature: What’s The Best Way To P...
Last Post: xSicKxBot
Today 12:48 AM
» Replies: 0
» Views: 4
News - How Cyberpunk 2077 Cross-Saves Wo...
Last Post: xSicKxBot
Today 12:48 AM
» Replies: 0
» Views: 5

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020