Is there a way to efficiently concatenate str and list?
inside = [] #a list of Items
class Backpack:
def add(toadd):
inside += toadd
print "Your backpack contains: " #now what do I do here?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It sounds like you’re just trying to add a string to a list of strings. That’s just
append:There’s nothing specific here to strings; the same thing works for a list of
Iteminstances, or a list of lists of lists of strings, or a list of 37 different things of 37 different types.In general,
appendis the most efficient way to concatenate a single thing onto the end of a list. If you want to concatenate a bunch of things, and you already have them in a list (or iterator or other sequence), instead of doing them one at a time, useextendto do them all at once, or just+=instead (which means the same thing asextendfor lists):If you want to later concatenate that list of strings into a single string, that’s the
joinmethod, as RocketDonkey explains:I’m guessing you want to get a little fancier and put an “and” between the last to things, skip the commas if there are fewer than three, etc. But if you know how to slice a list and how to use
join, I think that can be left as an exercise for the reader.If you’re trying to go the other way around and concatenate a list to a string, you need to turn that list into a string in some way. You can just use
str, but often that won’t give you what you want, and you’ll want something like thejoinexample above.At any rate, once you have the string, you can just add it to the other string:
If you have a list of things that aren’t strings and want to add them to the string, you have to decide on the appropriate string representation for those things (unless you’re happy with
repr):Notice that just calling
stron a list ofItems callsrepron the individual items; if you want to callstron them, you have to do it explicitly; that’s what thestr(i) for i in insidepart is for.Putting it all together:
When you run this, it will print: