python结尾空格_Python字符串结尾有空格和没有空格,并且是不变性的

这是CPython实现如何选择缓存字符串文本的一个怪癖。具有相同内容的字符串文本可以引用同一个字符串对象,但它们不必引用。'string'恰好在'string '不存在时被自动截取,因为'string'只包含Python标识符中允许的字符。我不知道为什么他们会选择这个标准,但事实确实如此。在不同的Python版本或实现中,行为可能不同。在

来自cpython2.7源代码,^{},第28行:Interning strings (ob_sstate) tries to ensure that only one string

object with a given value exists, so equality tests can be one pointer

comparison. This is generally restricted to strings that "look like"

Python identifiers, although the intern() builtin can be used to force

interning of any string.

您可以在^{}中看到执行此操作的代码:/* Intern selected string constants */

for (i = PyTuple_Size(consts); i >= 0; ) {

PyObject *v = PyTuple_GetItem(consts, i);

if (!PyString_Check(v))

continue;

if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))

continue;

PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));

}

另外,请注意,interning与Python字节码编译器合并字符串文本是一个独立的过程。如果让编译器一起编译a和b赋值,例如将它们放在一个模块或一个if True:中,您会发现a和{}将是同一个字符串。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值