0

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}

Arun G
  • 1,678
  • 15
  • 17

4 Answers4

1

Don't use concatenation: use the implicit joining that happens inside parentheses.

my_string = (
    '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)
)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

Surround your string with parentheses, you also won't need the + and \ anymore:

('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)
CMDej
  • 294
  • 2
  • 7
1

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
jurasource
  • 406
  • 5
  • 6
1
my_string = (
    '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)
Roshan
  • 1,459
  • 1
  • 14
  • 20