-1

I'm trying to insert my list values (test) into a variable (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)

When I run the following command I get.

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
)

What I would like is (with or without the ' marks):

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

I've tried rstrip(), strip(), and removing \n etc but to no avail. I can get it to insert just one value absolutely fine but iterating over the string with the list seems to be the problem. Any help is greatly appreciated.

3 Answers3

1

Your use has the result of the following string

"api.user_timeline(screen_name = ['test', 'test1', 'test2', 'test3'], count = 10, wait_on_rate_limit = True)"

You need to use a list comprehension

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)
rioV8
  • 24,506
  • 3
  • 32
  • 49
0

You need to iterate over the test items.

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)
chrisharrel
  • 337
  • 2
  • 10
0

You used format to insert the whole test list into your string and assign the result to the users variable. But iterating over the string (stored in the users variable) gives you every character as an input on every loop. To achieve what you expect you should iterate over items in your list stored in test variable - and use them as a parameter of format method. Look below:

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

The result of the execution:

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)

If you need quotation marks in output simple add " to your users value template:

users = "'api.user_timeline(screen_name = {}, count = 10, wait_on_rate_limit = True)'"