如何使用for循环粘贴字符串?

时间:2017-11-27 21:32:48

标签: python

我想使用python3遍历将相同项目粘贴到更大字符串中的项目列表

这就是我到目前为止:

file_list = ['car', 'bike', 'bus']

for file in file_list: 
    print("taking a %s is better than other options because %s's let you get around the city faster" %(file))

我最终得到了一个TypeError:没有足够的格式字符串参数。

我最终想要的是三个单独的语句作为字符串。

  1. 选择汽车比其他选项更好,因为汽车可让您更快地到达城市
  2. 选择自行车比其他选项更好,因为自行车可让您更快地到达城市
  3. 乘坐巴士比其他选项更好,因为巴士可让您更快地到达城市

3 个答案:

答案 0 :(得分:2)

您可以使用字符串格式:

file_list = ['car', 'bike', 'bus']
for i, a in enumerate(file_list, 1):
   print("{n}. taking a {vehicle} is better than other options because {vehicle}'s let you get around the city faster".format(n=i, vehicle=a))

输出:

1. taking a car is better than other options because car's let you get around the city faster
2. taking a bike is better than other options because bike's let you get around the city faster
3. taking a bus is better than other options because bus's let you get around the city faster

答案 1 :(得分:1)

str.format(新式格式)与编号的掌上电脑一起使用:

for file in file_list: 
    print("taking a {0} is better than other options because \
           {0}'s let you get around the city faster".format(file))

0这里是指传递给str.format的第一个参数,这是这里唯一的参数。

答案 2 :(得分:0)

你错过了简单的事情

我猜你已经知道你哪里错了

file_list = ['car', 'bike', 'bus']

for file in file_list: 
    print("taking a %s is better than other options because %s's let you get around the city faster" %(file,file))
相关问题