Home > Blockchain >  how to concanate str with a list
how to concanate str with a list

Time:08-03

elem_1 = ['Hydrogen', 'Helium'] 
elem_2 = ['Lithium', 'Beryllium', 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon']
elem_3 = ['Sodium', 'Magnesium', 'Aluminum', 'Silicon', 'Phosphorus', 'Sulfur', 'Chlorine', 
'Argon']
print("Row 1:"   elem_1)
print("Row 2:"   elem_2)
print("Row 3:"   elem_3)

Right now it gives TypeError: can only concatenate str (not "list") to str

I want the output to look like this:

Row 1: Hydrogen, Helium
Row 2: Lithium, Beryllium, Boron, Carbon, Nitrogen, Oxygen, Fluorine, Neon
Row 3: Sodium, Magnesium, Aluminum, Silicon, Phosphorus, Sulfur, Chlorine, Argon

CodePudding user response:

Use join

print("Row 1: "   ', '.join(elem_1))
print("Row 2: "   ', '.join(elem_2))
print("Row 3: "   ', '.join(elem_3))

From the docs:

str.join(iterable)

Return a string which is the concatenation of the strings in iterable.

CodePudding user response:

In versions of python 3.6 and higher you can use f-strings. Then you can evaluate code within curly brackets

print(f"Row 1: {','.join(elem_1)}")

Other types of string interpolation can be found in

https://peps.python.org/pep-0498/

  • Related