PY: Url Encode without variable name

Is there a way in python to encode a list of URLs without variable names? for example,
q = ['with space 1', 'with space 2']
in qescaped = ['with% 20space1', 'with% 20space2']

+3
source share
2 answers

You can use urllib.quote along with map :

import urllib
q = ['with space1', 'with space2']
qescaped = map(urllib.quote, q)
+7
source

List comprehension is currently the Pythonic method for this:

q = [ 'with space1', 'with space2' ]
qescaped = [ urllib.quote(u) for u in q ]

Often you do not even need to create this list, but you can use the generator itself instead:

qescapedGenerator = (urllib.quote(u) for u in q)

(This saves memory and, if you do not need all the elements, also computation time.)

Many generators can also process generators:

urlsInLines = '\n'.join(urllib.quote(u) for u in q)

for escapedUrl in (urllib.quote(u) for u in q):
    print escapedUrl

- , list() .

0

Source: https://habr.com/ru/post/1704179/


All Articles