简体   繁体   中英

Confusion regarding str.format()

I am constructing a URL and injecting some params using requests library,

QUERY_PARAMS['q'] = r'test="{}"'.format(0012000017421)

This gives the expected: 'test="1342185233"'

But when I use the requests library to make a request like this:

result = requests.get(urlparse.urljoin(URL_TEST, URL_SEARCH), params=QUERY_PARAMS)

On my print statement I get a totally different number:

print('Searching with params: ', QUERY_PARAMS, ' on URL: ', result.url)

>>>('Searching with params: ', {'q': 'test="1342185233"', 'pretty_print': True, 'dataset': 'pod_nutrition_us'}, ' on URL: ', u'https://example.com/api/records/1.0/search?q=test%3D%221342185233%22&pretty_print=True&dataset=pod_nutrition_us')

How did this 1342185233 number come up when I use 0012000017421?

If, however, do this:

QUERY_PARAMS['q'] = r'test="0012000017421"'

This works correctly and the print statement above prints correctly what I want. Why does this occur?

In Python2, a literal number starts with 0 is in octal.

>> 011 == 9
True

In Python3, it's slightly different,

octal literals must now be specified with a leading "0o" or "0O" instead of "0";

which reduces the chance of making mistake.

You are passing the number instead of string in the format function. And since your number starts with zero, Python2 considers it to be an octal.

You can add quotes around your number and pass it in format function.

QUERY_PARAMS['q'] = r'test="{}"'.format('0012000017421')

This should do the work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM