Access out-of-loop variable for

Asked

Viewed 116 times

0

As access to variable cookies out of the loop?

cookies = []
for i in get_cookies(url):
   cookies = '='.join(i) + '; '
print(cookies)

Is just returning this:

personalization_id="v1_8yKL+7c5RUQ+HHELlnh5dw==";

I need you to return everyone else in one line, when I give print(i), is returning:

('_twitter_sess', 'BAh7CSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCDzJKCprAToMY3NyZl9p%250AZCIlMDY3NjhlNWQ2NzIwZWIzOWFhOGY4YmNjM2QyZTJlODY6B2lkIiU3OTY2%250AMmM1YjYzYmViYTgxYmZhNDM5OWVjYzJiMzU3Mg%253D%253D--1986635940f2d9bf0f775422f9999122b0279d8c')('ct0', '94d313ad03ce413f521761c16b4bfb63')('guest_id', 'v1%3A155978044447406891')('personalization_id', '"v1_8yKL+7c5RUQ+HHELlnh5dw=="')

I need you to stay like this:

_twitter_sess=BAh...; ct0=123... so on and so forth

  • William was not clear his doubt could explain better?

  • 1

    If the idea is to concatenate everything you need to do cookies += instead of cookies =

1 answer

0


Your code:

cookies = []
for i in get_cookies(url):
   cookies = '='.join(i) + '; '
print(cookies)

You defined cookies as a list, but wants the result to be a string; within the repeat loop you are overriding the value of cookies, that is, the previous value will always be lost. So, after finishing the loop, only the last cookie will be in cookies.

To fix it you 1) correctly starts the variable cookies and 2) uses concatenation instead of assignment within the loop.

cookies = ''
for i in get_cookies(url):
   cookies += '='.join(i) + '; '
print(cookies)

But it’s Python, you don’t have to do it all by hand, just use the tools that language gives you:

cookies = ';'.join(f'{name}: {value}' for name, value in get_cookies(url))
  • This worked, I just asked another question similar to this, I could not edit :/, but this solved guy, thanks anyway.

  • the code works, but note that there is no reason to have that for there.

  • 1

    ah - I’ve confused one thing here. yes need :-) (I’ll delete the comments)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.