Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to format this string with % arguments according to PEP8

Tags:

python

pep8

url_base = ("https://maps.googleapis.com/maps/api/place/search/json?"
            "location=%s,%s&radius=500&types=food|doctor&sensor=false&"
            "key=%s&pagetoken=%s") % (
    r['lat'],
    r['lng'],
    YOUR_API_KEY,
    ''
)

While formatted as shown above I have no underlines in SublimeText regarding PEP8, but it looks weird to me. How can I format it:

a) better (code is more readable)

b) still according to PEP8?

like image 262
andilabs Avatar asked Dec 08 '25 09:12

andilabs


2 Answers

Perhaps what makes it look weird to you is the way the very long string is being broken up to conform with PEP8. However, if you do need to break up a very long string, you are doing it the right way. Two juxtaposed strings are automatically concatenated by Python.

In your particular situation you don't need to write a very long string, however. Instead, you could use urllib.urlencode to format the parameters for you:

import urllib
url_base = "https://maps.googleapis.com/maps/api/place/search/json?"
params = urllib.urlencode(
    {'location': '{},{}'.format(r['lat'], r['lng']),
     'radius': 500,
     'types': 'food|doctor',
     'sensor': 'false',
     'key': YOUR_API_KEY,
     'pagetoken': ''
     })
url = url_base + params
like image 157
unutbu Avatar answered Dec 09 '25 22:12

unutbu


from urlparse import urlunparse

query_params = { "location": "%s,%s" % (r['lat'], r['lng']),
                 "radius": "500",
                 "types": "food|doctor",
                 "sensor": "false",
                 "key": YOUR_API_KEY,
                 "pagetoken": ""
}

url_base = (urlunparse(("https", "maps.googleapis.com",
                       "/maps/api/place/search/json", None,
                       "&".join("=".join(qp) for qp in query_params.items()),
                       None)),
)

Remember though, PEP8 are guidelines and suggestions, not a hard set of rules.

like image 32
Sean Perry Avatar answered Dec 09 '25 21:12

Sean Perry