python比较两个字符串的不同_当您在python中比较两个字符串时会发生什么

When comparing strings in python e.g.

if "Hello" == "Hello":

#execute certain code

I am curious about what the code is that compares the strings. So if i were to compare these in c i would just compare each character and break when one character doesn't match. i'm wondering exactly what the process is of comparing two strings like this, i.e. when it will break and if there is any difference between this comparison and the method said above other than redundancy in lines of code

解决方案

I'm going to assume you are using CPython here, the standard Python.org implementation. Under the hood, the Python string type is implemented in C, so yes, testing if two strings are equal is done exactly like you'd do it in C.

What it does is use the memcmp() function to test if the two str objects contain the same data, see the unicode_compare_eq function defined in unicodeobject.c:

static int

unicode_compare_eq(PyObject *str1, PyObject *str2)

{

int kind;

void *data1, *data2;

Py_ssize_t len;

int cmp;

len = PyUnicode_GET_LENGTH(str1);

if (PyUnicode_GET_LENGTH(str2) != len)

return 0;

kind = PyUnicode_KIND(str1);

if (PyUnicode_KIND(str2) != kind)

return 0;

data1 = PyUnicode_DATA(str1);

data2 = PyUnicode_DATA(str2);

cmp = memcmp(data1, data2, len * kind);

return (cmp == 0);

}

This function is only called if str1 and str2 are not the same object (that's an easy and cheap thing to test). It first checks if the two objects are the same length and store the same kind of data (string objects use a flexible storage implementation to save memory; different storage means the strings can't be equal).

There are other Python implementations, like Jython or IronPython, which may use different techniques, but it basically will come down to much the same thing.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值