Home > OS >  Having issue with Python input
Having issue with Python input

Time:07-08

My python code looks like below. Basically, I am joining two part of url using urljoin module of urlib. The issue that I am facing is during the URL join my output looks like below. As shown below the input from a which is a list is getting displayed at start part of url and end has start information. My expected output is also mentioned below.

To summarize, I want user to input total number of terms and the entered terms should be passed into query part of URL (i.e. query[]=" "&query[]= " "). Not sure if I am missing something.

Thanks in advance for help!

Code

from urllib.parse import urljoin

num_terms=int(input("Enter total number of search terms:")) #Asking user for number of terms

a=input("Enter all search terms: ").split(",",num_terms) #User enters all the terms

start,end=input("Enter start and end date").split() #User enters start and end date

base_url="http://mytest.org"
join_url="/comments/data?" "terms[]={}" "&terms[]={}"*int(num_terms-1) "&start={}&end={}".format(a,start,end)

url=urljoin(base_url,join_url) #Joining url
url

Output:

Enter total number of search terms:3
Enter all search terms: ty ou io
Enter start and end date2345 7890
"http://mytest.org/comments/data?terms[]={}&terms[]={}&terms[]={}start=['ty ou io']&end=2345"

Expected Output

"http://mytest.org/comments/data?terms[]=ty&terms[]=ou&terms[]=io&start=2345&end=7890"

CodePudding user response:

One problem is your code is only formatting the last bit of the url. That is,

"&start={}&end={}".format(a,start,end)

is the only part where the formatting applies; you need to add parentheses.

The other thing is that we need to unpack the list of terms, a, in the .format function:

join_url=("/comments/data?" "terms[]={}" "&terms[]={}"*int(num_terms-1) "&start={}&end={}").format(*a,start,end)

But I'd recommend using f-strings instead of .format:

join_url=("/comments/data?" '&'.join([f"terms[]={term}"for term in a]) f"&start={start}&end={end}")

(I also used str.join for the terms instead of string multiplication.)

CodePudding user response:

A simple for loop should suffice:

terms = ""
for i in range(num_terms):
    terms  = f"terms[]={a[i]}&"

Basically, format takes a single value, it does not iterate over a list as you wanted. This is a simple way to achieve your goal. You could probably use list comprehension as well.

[f"terms[]={term}"for term in a]

Output:

Enter total number of search terms:3
Enter all search terms: au,io,ua
Enter start and end date233 444
http://mytest.org/comments/data?terms[]=au&terms[]=io&terms[]=ua&&start=233&end=444
  • Related