I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example:
list1 = ['foo', 'fob', 'faz', 'funk'] string = 'bar' *magic* list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar']
I tried for loops, and an attempt at list comprehension, but it was garbage. As always, any help, much appreciated.
To append string to beginning of list we have used [a] + l1 and the string will get appended to the list at the beginning.
You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.
The simplest way to do this is with a list comprehension:
[s + mystring for s in mylist]
Notice that I avoided using builtin names like list
because that shadows or hides the builtin names, which is very much not good.
Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):
(s + mystring for s in mylist)
These are very powerful, flexible, and concise. Every good python programmer should learn to wield them.
my_list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' my_new_list = [x + string for x in my_list] print my_new_list
This will print:
['foobar', 'fobbar', 'fazbar', 'funkbar']
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