Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string with array values

Tags:

python

arrays

I'm using Python and want to be able to create an array and then concatenate the values with a string in a certain format. I'm hoping below will explain what I mean.

name_strings = ['Team 1', 'Team 2']
print "% posted a challenge to %s", %(name_strings)

Where each value from name_strings will be placed in the %s spot. Any help is much appreciated.

like image 401
zee Avatar asked Aug 21 '26 22:08

zee


2 Answers

One way might be to expand the array in to the str format function...

array_of_strings = ['Team1', 'Team2']
message = '{0} posted a challenge to {1}'
print(message.format(*array_of_strings))
#> Team1 posted a challenge to Team2
like image 65
cjhanks Avatar answered Aug 24 '26 13:08

cjhanks


You're very close, all you need to do is remove the comma in your example and cast it to a tuple:

print "%s posted a challenge to %s" % tuple(name_strings)

Edit: Oh, and add that missing s in %s as @falsetru pointed out.

Another way of doing it, without casting to tuple, is through use of the format function, like this:

print("{} posted a challenge to {}".format(*name_strings))

In this case, *name_strings is the python syntax for making each element in the list a separate argument to the format function.

like image 22
Herman Schaaf Avatar answered Aug 24 '26 11:08

Herman Schaaf