False (我想这与 Python 的字符串比较/ASCII 函数完成后的字符串编码有关。) 最佳答案 那是因为a-6ren">
gpt4 book ai didi

python - 为什么这个 Python ascii 字符串不等同于常规字符串?

转载 作者:行者123 更新时间:2023-11-28 21:58:55 25 4
gpt4 key购买 nike

为什么以下会失败?

assert ascii("cat") == "cat" => False

(我想这与 Python 的字符串比较/ASCII 函数完成后的字符串编码有关。)

最佳答案

那是因为ascii的输出是这样的:

>>> ascii('cat')
"'cat'"

这明显不同于 'cat'

ascii 返回字符串对象的 repr 版本,可与 evalast.literal_eval 重新生成字符串对象。

>>> eval (ascii('cat'))
'cat'
>>> from ast import literal_eval
>>> literal_eval(ascii('cat'))
'cat'

来自docs :

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr(). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings and floating point numbers, in particular, have two distinct representations.

关于python - 为什么这个 Python ascii 字符串不等同于常规字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17418817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com