Search code examples
pythondjangopep

please suggest me the best practice in sting-value formating


i have a long string like below which i m trying to format aswel aligning it with PEP standards

'http://abc/api/run=1&'+ \
            'actionData=[{"query":"air-{0}-{1}-{2}--1-0-0-E-111--"},{"query":"hotels-{1}-{3}-{4}-1-1_0-"},{"query":"air-{1}-{0}-{5}--1-0-0-E-111--"}]'+ \
            '&tripOrigin={0}&tripDestination={1}'.format(origin.get('vcid'), destination.get('vcid'), onward_f_date, check_in_date, check_out_date, return_f_date)

But ran in to output like be this

'http://abc/api/run=1&actionData=[{"query":"air-{0}-{1}-{2}--1-0-0-E-111--"},{"query":"hotels-{1}-{3}-{4}-1-1_0-"},{"query":"air-{1}-{0}-{5}--1-0-0-E-111--"}]&tripOrigin=2311443&tripDestination=123445667'

expecting formatting happen all the {0}, {1}, {2}, {3}, {4} and {5}


Solution

  • You need to escape the curly braces that don't correspond to formatting placeholders.

    Eg: This

    'actionData=[{"query":"air-{0}-{1}-{2}--1-0-0-E-111--"}
    

    Should look like:

    'actionData=[{{"query":"air-{0}-{1}-{2}--1-0-0-E-111--"}}
    

    So:

    >>> print 'http://abc/api/run=1&actionData=[{{"query":"air-{0}-{1}-{2}--1-0-0-E-111--"}},{{"query":"hotels-{1}-{3}-{4}-1-1_0-"}},{{"query":"air-{1}-{0}-{5}--1-0-0-E-111--"}}]&
    tripOrigin={0}&tripDestination={1}'.format(999,999,999,999,999,999)
    
    http://abc/api/run=1&actionData=[{"query":"air-999-999-999--1-0-0-E-111--"},{"query":"hotels-999-999-999-1-1_0-"},{"query":"air-999-999-999--1-0-0-E-111--"}]&tripOrigin=999&tripDestination=999