Reputation: 35
I want to add text to each item in a list and then it back into the list.
Example
foods = [pie,apple,bread]
phrase = ('I like')
statement = [(phrase) + (foods) for phrase in foods]
I want to have the output (I like pie, I like apple, I like bread)
It prints out something along the lines of (hI like,pI like,pI like)
Upvotes: 1
Views: 601
Reputation: 6099
You should avoid declaring phrase on another line, here is the sample that should make it.
statement = ['I like ' + food for food in foods] # Note the white space after I like
In your code you probably coded it too quickly because you are reasigning the value of phrase with the for phrase in foods
. Also when you do phrase + foods
foods is a list which cannot be concatenated with string
Upvotes: 2
Reputation: 16593
I prefer string formatting:
foods = ['pie','apple','bread']
phrase = 'I like'
statement = ['{0} {1}'.format(phrase, j) for j in foods]
# Python 3.6+
statement = [f'{phrase} {j}' for j in foods]
Upvotes: 1
Reputation: 7404
foods = ['pie','apple','bread']
phrase = 'I like'
statement = [phrase + ' ' + j for j in foods]
>>> statement
['I like pie', 'I like apple', 'I like bread']
The problem in your code was that you were using the iterator incorrectly.
Upvotes: 0
Reputation: 4343
You can also create a container and use .format
:
phrase = 'I like {}'
statement = [phrase.format(food) for food in ("pie","apple","bread")]
Upvotes: 0