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'
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With