【问题标题】:How to iterate over a for loop with .format如何使用 .format 遍历 for 循环
【发布时间】:2020-11-29 15:11:07
【问题描述】:

我正在尝试将我的列表值(测试)插入到变量(用户)中。

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() 和删除 \n 等,但无济于事。我可以让它只插入一个值,绝对没问题,但是用列表迭代字符串似乎是问题所在。非常感谢任何帮助。

【问题讨论】:

    标签: python python-3.x for-loop string.format f-string


    【解决方案1】:

    您使用 format 将整个测试列表插入到您的字符串中,并将结果分配给 users 变量。但是遍历字符串(存储在 users 变量中)会给你每个字符作为每个循环的输入。为了达到您的期望,您应该迭代存储在测试变量中的列表中的项目 - 并将它们用作格式方法的参数。往下看:

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

    【讨论】:

      【解决方案2】:

      您需要迭代测试项目。

      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)
      

      【讨论】:

        【解决方案3】:

        你的使用有以下字符串的结果

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

        【讨论】:

          猜你喜欢
          • 2011-08-07
          • 2020-06-17
          • 1970-01-01
          • 2020-11-17
          • 1970-01-01
          • 2021-04-02
          • 1970-01-01
          • 1970-01-01
          • 2013-02-20
          相关资源
          最近更新 更多