pythonstringloops

Add multiple unknowns to a string in Python


I need to add four values ​​of possible coordinates instead of "item" value to the following line:

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

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 want to obtain 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


Solution

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