Python 如何使用.format迭代for循环
我正在尝试将我的列表值测试插入变量users中Python 如何使用.format迭代for循环,python,python-3.x,for-loop,string.format,f-string,Python,Python 3.x,For Loop,String.format,F String,我正在尝试将我的列表值测试插入变量users中 test = ['test', 'test1', 'test2', 'test3'] users = 'api.user_timeline(screen_name = {}, count = 10, wait_on_rate_limit = True)'.format(test) for user in users: print(user) 当我运行下面的命令时,我得到了 a p i . u s e r _ t i m e l i n
test = ['test', 'test1', 'test2', 'test3']
users = 'api.user_timeline(screen_name = {}, count = 10, wait_on_rate_limit = True)'.format(test)
for user in users:
print(user)
当我运行下面的命令时,我得到了
a
p
i
.
u
s
e
r
_
t
i
m
e
l
i
n
e
(
s
c
r
e
e
n
_
n
a
m
e
=
[
'
t
e
s
t
'
,
'
t
e
s
t
1
'
,
'
t
e
s
t
2
'
,
'
t
e
s
t
3
'
]
,
c
o
u
n
t
=
1
0
,
w
a
i
t
_
o
n
_
r
a
t
e
_
l
i
m
i
t
=
T
r
u
e
)
我想要的是有或没有“标记:
'api.user_timeline(screen_name = test, count = 10, wait_on_rate_limit = True)'
'api.user_timeline(screen_name = test1, count = 10, wait_on_rate_limit = True)'
'api.user_timeline(screen_name = test2, count = 10, wait_on_rate_limit = True)'
'api.user_timeline(screen_name = test3, count = 10, wait_on_rate_limit = True)'
我尝试过rstrip、strip和removing \n等,但没有效果。我可以让它只插入一个值,这是绝对正确的,但是用列表遍历字符串似乎是个问题。非常感谢您的帮助。您的使用结果如下:
"api.user_timeline(screen_name = ['test', 'test1', 'test2', 'test3'], count = 10, wait_on_rate_limit = True)"
您需要使用列表
test = ['test', 'test1', 'test2', 'test3']
users = ['api.user_timeline(screen_name = {}, count = 10, wait_on_rate_limit = True)'.format(t) for t in test]
for user in users:
print(user)
您需要迭代测试项
test = ['test', 'test1', 'test2', 'test3']
users = ['api.user_timeline(screen_name = {0}, count = 10, wait_on_rate_limit = True)'.format(user) for user in test]
for user in users:
print(user)
您使用format将整个测试列表插入字符串,并将结果分配给users变量。但是,对存储在users变量中的字符串进行迭代会将每个字符作为每个循环的输入。为了达到预期效果,您应该迭代存储在测试变量中的列表中的项,并将它们用作format方法的参数。请看下面:
test = ['test', 'test1', 'test2', 'test3']
users = 'api.user_timeline(screen_name = {}, count = 10, wait_on_rate_limit = True)'
for tst in test:
print(users.format(tst))
执行结果:
api.user_timeline(screen_name = test, count = 10, wait_on_rate_limit = True)
api.user_timeline(screen_name = test1, count = 10, wait_on_rate_limit = True)
api.user_timeline(screen_name = test2, count = 10, wait_on_rate_limit = True)
api.user_timeline(screen_name = test3, count = 10, wait_on_rate_limit = True)
如果在“输出简单”中需要引号,请添加到用户值模板:
users = "'api.user_timeline(screen_name = {}, count = 10, wait_on_rate_limit = True)'"