3

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.

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2
  1. Remove ,:

    print "% posted a challenge to %s", %(name_strings)
    #                                 ^
    
  2. The format specifier is incomplete. Replace it with %s.

    print "% posted a challenge to %s" %(name_strings)
    #      ^
    
  3. String formatting operation require a tuple, not a list : convert the list to a tuple.

    name_strings = ['Team 1', 'Team 2']
    print "%s posted a challenge to %s" % tuple(name_strings)
    
  4. If you are using Python 3.x, print should be called as function form:

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

Alternative using str.format:

name_strings = ['Team 1', 'Team 2']
print("{0[0]} posted a challenge to {0[1]}".format(name_strings))

Comments

0
concatenated_value = ' posted a challenge to '.join(name_strings)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.