Hayden
Hayden

Reputation: 498

How to place the iterated string variable in another string

Quick overview: I am writing a a very simple script using Python and Selenium to view Facebook Metrics for multiple Facebook pages.

I am trying to find a clean way to loop through the pages and output their results (it's only one number that I am collecting).

Here is what I have right now but it is not working.

# Navigate to metrics page

pages = ["page_example_1", "page_example_2", "page_example_3"]

for link in pages:
    browser.get(('https://www.facebook.com/{link}/insights/?section=navVideos'))

Upvotes: 1

Views: 45

Answers (2)

Todor Minakov
Todor Minakov

Reputation: 20047

It didn't work for you, because you aimed to use Python 3.6's f-strings, but forgot to prepend your string with the f char - crucial for this syntax. E.g. your code should be (only the relevant part):

browser.get(f'https://www.facebook.com/{link}/insights/?sights/?section=navVideos')

Alternatively you could use string formatting (e.g. the established approach before 3.6):

browser.get('https://www.facebook.com/{}/insights/?sights/?section=navVideos'.format(link))

In general, string concatenation - 'string1' + variable + 'string2' - is discouraged in python for performance and readability reasons.


BTW, in your sample code you had brackets around the get()'s argument - it is browser.get((arg)), which essentially turned it to a tuple, and might've caused error in the call. Not sure was it a typo or on purpose, as you can see I and the other responders have removed it.

Upvotes: 1

Ishan Srivastava
Ishan Srivastava

Reputation: 1189

# Navigate to metrics page

pages = ["page_example_1", "page_example_2", "page_example_3"]

for link in pages:
    browser.get('https://www.facebook.com/'+ link + '/insights/?section=navVideos')

its just string concatenation or if you are so much inclined to use that syntax, have a look at the comment by @heather

Upvotes: 2

Related Questions