Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python concatenate string & list

Tags:

I have a list and string:

fruits = ['banana', 'apple', 'plum'] mystr = 'i like the following fruits: ' 

How can I concatenate them so I get (keeping in mind that the enum may change size) 'i like the following fruits: banana, apple, plum'

like image 206
user1705110 Avatar asked Sep 28 '12 02:09

user1705110


People also ask

How do you concatenate 2 strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

Can you concatenate F strings in Python?

String Concatenation using f-stringIf you are using Python 3.6+, you can use f-string for string concatenation too. It's a new way to format strings and introduced in PEP 498 - Literal String Interpolation. Python f-string is cleaner and easier to write when compared to format() function.


2 Answers

Join the list, then add the strings.

print mystr + ', '.join(fruits) 

And don't use the name of a built-in type (str) as a variable name.

like image 65
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 11:09

Ignacio Vazquez-Abrams


You can use this code,

fruits = ['banana', 'apple', 'plum', 'pineapple', 'cherry'] mystr = 'i like the following fruits: ' print (mystr + ', '.join(fruits)) 

The above code will return the output as below:

i like the following fruits: banana, apple, plum, pineapple, cherry 
like image 39
mbgsuirp Avatar answered Sep 28 '22 11:09

mbgsuirp