简体   繁体   English

关于str.format()的困惑

[英]Confusion regarding str.format()

I am constructing a URL and injecting some params using requests library, 我正在构造一个URL并使用requests库注入一些参数,

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

This gives the expected: 'test="1342185233"' 这给出了预期的结果: '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? 当我使用0012000017421时,这1342185233号是怎么出现的?

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. 在Python2中,以0开头的立即数是八进制形式。

>> 011 == 9
True

In Python3, it's slightly different, 在Python3中,它略有不同,

octal literals must now be specified with a leading "0o" or "0O" instead of "0"; 八进制文字现在必须以“ 0o”或“ 0O”开头而不是“ 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. 并且由于您的数字从零开始,因此Python2认为它是八进制的。

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. 这应该做的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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