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
Code:
['learn ', 'python ', 'fast']
to the string
Code:
'learn python fast'
.

Solution: to convert a list of strings to a string, do the following.
  • Call the
    Code:
    ''.join(list)
    method on the empty string
    Code:
    ''
    that glues together all strings in the
    Code:
    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:
    ''
    .

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

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

The output is:

Code:
learn python fast

Try it yourself in our interactive Python shell:

https://repl.it/@finxter/joinpythonstringlist?lite=true

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

Code:
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
    Code:
    ''.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
    Code:
    [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
    Code:
    ''.join(newlist)
    method.

  • Method 4: Use the map function
    Code:
    map(str, list]
    if the list contains elements of different types to convert all elements to the string data type. Combine them using the
    Code:
    ''.join(newlist)
    method.

Here are all four variants in some code:

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:

https://repl.it/@finxter/listtostring?lite=true

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
Code:
['learn', 'python', 'fast']
to the string
Code:
'learn,python,fast'
.

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

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

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

The output is:

Code:
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
Code:
['learn', 'python', 'fast']
to the string
Code:
'learn python fast'
. (Note the empty spaces between the terms.)

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

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

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

The output is:

Code:
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
Code:
['learn', 'python', 'fast']
to the string
Code:
'learn\npython\nfast'
or as a multiline string:

Code:
'''learn python fast'''

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

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

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

The output is:

Code:
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
Code:
['learn', 'python', 'fast']
to the string
Code:
'"learn", "python", "fast"'
:

Solution: to convert a list of strings to a string, call the
Code:
', '.join('"' + x + '"' for x in lst)
method on the delimiter string
Code:
', '
that glues together all strings in the
Code:
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
Code:
"
chararacter.

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

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

The output is:

Code:
"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
Code:
['learn', 'python', 'fast']
to the string
Code:
'[learn, python, fast]'
:

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

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

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

The output is:

Code:
[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
Code:
['learn', 'python', 'fast']
to a string
Code:
"['learn', 'python', 'fast']"
and back to a list
Code:
['learn', 'python', 'fast']
.

Solution: Use the following two steps to convert back and forth between a string and a list:
  • Use the built-in
    Code:
    str()
    function to convert from a list to a string.

  • Use the built-in
    Code:
    eval()
    function to convert from a string to a list.

Code:
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
Code:
string
for the former and
Code:
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
Code:
[1, 2, 3]
to a string
Code:
'123'
.

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

Code:
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
Code:
TypeError
:

Code:
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
    Code:
    ''.join(list)
    method to glue together all list elements to a single string.

  • Use the list comprehension method
    Code:
    [str(x) for x in lst]
    to convert all list elements to type string.

  • Use
    Code:
    str(list)
    to convert the list to a string representation.

Here are three examples:

Code:
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!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: