Reputation: 3171
I have list of values:
md5 = ['1111', '3333', '44444', '555555', '56632423', '23423514', '2342352323']
I want to concatenate them into a Query String:
'md5=1111&md5=3333&md5=44444&md5=555555&md5=56632423&md5=23423514&md5=2342352323'
What is the best way to do that?
Upvotes: 1
Views: 5827
Reputation: 59148
Since you're building a query string, it's better to use a function from the standard library that's specifically designed to do so:
urllib.parse.urlencode()
(in Python 3)urllib.urlencode()
(in Python 2)... than to muck around with str.join()
. Here's how you'd use it:
from urllib.parse import urlencode # Python 3
# from urllib import urlencode # Python 2
md5 = ['1111', '3333', '44444', '555555', '56632423', '23423514', '2342352323']
urlencode([("md5", x) for x in md5])
Result:
'md5=1111&md5=3333&md5=44444&md5=555555&md5=56632423&md5=23423514&md5=2342352323'
Alternatively (thanks to Jon Clements in the Python chatroom), you can pass a dictionary to urlencode and the parameter doseq=True
:
urlencode({'md5': md5}, doseq=True)
... which produces the same result. This is explained in the documentation linked above:
The value element in itself can be a sequence and in that case, if the optional parameter doseq is evaluates to True, individual
key=value
pairs separated by'&'
are generated for each element of the value sequence for the key. The order of parameters in the encoded string will match the order of parameter tuples in the sequence.
Upvotes: 15
Reputation: 365777
md5s = '&'.join('md5='+m for m in md5)
The part inside the parentheses is a generator expression, which gives you 'md5='+m
for each m
in the original list.
The join
function takes that expression and links it into one big string, putting an &
between each pair.
Upvotes: 5
Reputation: 122376
You can use join()
:
md5=['1111','3333','44444','555555','56632423','23423514','2342352323']
print 'md5=' + '&md5='.join(md5)
Upvotes: 0