Python 如何使用for循环粘贴字符串?
我想使用python3遍历一个项目列表,将相同的项目粘贴到一个更大的字符串中 这就是我迄今为止所做的:Python 如何使用for循环粘贴字符串?,python,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:没有足够的参数用于格
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:没有足够的参数用于格式化字符串
我想以三个单独的语句作为字符串结束
将
str.format
(新型格式)与编号的palceholder一起使用:
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
的第一个参数,这是此处唯一的参数。您可以使用字符串格式:
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
你错过了一件简单的事
我想你已经知道哪里错了
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))
我会把汽车、自行车和公共汽车称为
车辆
而不是文件
你可以用%
做类似的事情,使用命令
,但它很冗长:'%(f)s%%{f':file}
。(或者使用locals()
作为dict,并使用变量名本身作为格式字符串中的键。)@chepner Ok…太棒了<代码>枚举可以从1开始编号:枚举(文件列表,1)
。