Add multiple unknowns to a string in Pyton

Question:

I need to add to the line:

url="items.point&point1={item}%2C{item}&point2C{item}%2C{item}"

four values ​​of possible coordinates instead of "item" value. We have to generate these coordinate values ​​in a loop.

I tried many different options for how to do this, but the program displays a lot of extra values.

My code:

import numpy as np
coordinates=[]
for item in np.arange(45.024287,45.024295,0.000001):
    coordinates.append("%.6f" %item)
    for item in np.arange(45.024287,45.024295,0.000001):
        coordinates.append("%.6f" %item)
urls=[]
for item in (coordinates):
    urls.append(f"items.point&point1{item}%2C{item}&point2={item}%2C{item}")
print(urls)

I need to get this result:

"items.point&point1=45.024295%2C45.024295&point2=39.073557%2C45.005125","items.point&point1=45.024294%2C45.024294&point2=39.073557%2C45.005125"...Etc 

With different coordinates

But I am getting repeated values ​​due to the fact that the loop is in a loop.
Can you tell me how you can substitute several variables in a string without doubling the values?Please

Asked By: AnTiXrI

||

Answers:

I remember reading recently something related to your problem. Can’t remember the post, else I’d link it, but I took notes about the beautiful method! So try this:

urls=[]
for item1, item2 in zip(*[iter(coordinates)]*2):
    urls.append(f"items.point&point1{item1}%2C{item2}&point2=39.073557%2C45.005125")
print(urls)
Answered By: Swifty

There’s no need for the coordinates array. Just append to urls in the nested for loop to get all the combinations of item values.

for item1 in np.arange(45.024287,45.024295,0.000001):
    for item2 in np.arange(45.024287,45.024295,0.000001):
        urls.append(f"items.point&point1={item1}%2C{item2}&point2=39.073557%2C45.005125")
Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.