将字符串与数组值连接起来

3
我正在使用Python,并希望能够创建一个数组,然后以特定的格式将值与字符串连接起来。我希望下面的内容能够解释我的意思。
name_strings = ['Team 1', 'Team 2']
print "% posted a challenge to %s", %(name_strings)

每个name_strings中的值都将放置在%s的位置。非常感谢任何帮助。

4个回答

4

一种方法可能是将数组扩展到 str格式 函数中...

array_of_strings = ['Team1', 'Team2']
message = '{0} posted a challenge to {1}'
print(message.format(*array_of_strings))
#> Team1 posted a challenge to Team2

3

你很接近了,你只需要在你的示例中删除逗号并将其转换为元组:

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

编辑: 噢,正如@falsetru指出的那样,在%s中添加缺少的s

另一种方法是使用format函数,而无需转换为元组,像这样:

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

在这种情况下,*name_strings是Python语法,用于将列表中的每个元素作为单独的参数传递给format函数。

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))
    

使用 str.format 的另一种方法:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接