How to build String from List in Python

Python supports unstring from a string (also called slicing). In addition to that, you can convert a list into a String. The list is one of the data types. Here is How to create a list in the Python best example.

Advertisements

A list can have a group of data. That can be numbers, words, or letters. Here the idea is you can create a string by concatenating them all together.

String-list-python

How to convert a list into a string in 3 steps

In three steps, you can build a string from a list. Here are the detailed steps.

  • Create list with heterogeneous data
  • Use For loop
  • Build the string and print the output

1.Create list with heterogeneous data

List with values.

list_of_values = [1.0, 'this is a test', 2, 'c', 'hello 
world']

It has data of decimals, numbers, and words. Our aim is here to create a string by concatenating all.

How to build String from List in Python
Photo by Rahat Ali on Pexels.com

2. Use for loop

Here is for loop. Firstly, we print all the list values. Below is the logic for that.

list_of_values = [1.0, 'this is a test', 2, 'c', 'hello world']
for v in list_of_values:
print(v)

Output

1.0 
this is a test
2
c
hello world


** Process exited - Return Code: 0 **
Press Enter to exit terminal

What happened in the output? It displayed all the list values.

3. Build the string and print the output

You can build a string in two ways. One is with for loop, and print. The other one is using join and print.

a. For loop and Print method

list_of_values = [1.0, 'this is a test', 2, 'c', 'hello world']
for v in list_of_values:
print(v, end=' ') # Space included in end as separator

Output

1.0 this is a test 2 c hello world 

** Process exited - Return Code: 0 **
Press Enter to exit terminal

b. Join and print method

Using join method and print, you can build a string.

list_of_values = [1.0, 'this is a test', 2, 'c', 'hello world']
s = ' '.join([str(i) for i in list_of_values])
print(s)

Output

1.0 this is a test 2 c hello world 


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Related posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.