将两个字符串与“is"进行比较——未按预期执行 [英] comparing two strings with 'is' -- not performing as expected

查看:43
本文介绍了将两个字符串与“is"进行比较——未按预期执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用 is 比较两个字符串.一个字符串由函数返回,另一个只是在比较中声明.对象身份测试,但根据此页面,由于 Python 的内存优化,它也适用于两个相同的字符串.但是,以下不起作用:

I'm attempting to compare two strings with is. One string is returned by a function, and the other is just declared in the comparison. is tests for object identity, but according to this page, it also works with two identical strings because of Python's memory optimization. But, the following doesn't work:

def uSplit(ustring):
        #return user minus host
        return ustring.split('!',1)[0]

user = uSplit('theuser!host')
print type(user)
print user
if user is 'theuser':
    print 'ok'
else:
    print 'failed'

user = 'theuser'

if user is 'theuser':
    print 'ok'

输出:

type 'str'
theuser
failed
ok

我猜这是因为函数返回的字符串是不同的类型";字符串而不是字符串文字.反正有没有得到一个函数来返回一个字符串文字?我知道我可以使用 ==,但我只是好奇.

I'm guessing the reason for this is a string returned by a function is a different "type" of string than a string literal. Is there anyway to get a function to return a string literal? I know I could use ==, but I'm just curious.

推荐答案

你引用的网站是这样说的:

The site you quote says this:

如果两个字符串文字相等,则它们已被放置到相同的内存位置.

If two string literals are equal, they have been put to same memory location.

但是

uSplit('theuser!host')

不是字符串文字 -- 它是对文字 'theuser!host' 进行操作的结果.

is not a string literal -- it's the result of an operation on the literal 'theuser!host'.

无论如何,您通常不应该使用 is 检查字符串是否相等,因为无论如何这种内存优化只是您不应该依赖的实现细节.

Anyway, you usually shouldn't check for string equality using is, because this memory optimization in any case is just an implementation detail you shouldn't rely on.

此外,对于诸如 is None 之类的内容,您应该使用 is.用它来检查两个对象——你设计的类——是否是同一个实例.您不能轻松地将它用于字符串或数字,因为创建这些内置类的规则很复杂.一些字符串是实习的.类似地,一些数字被实习.

Also, You should use is for things like is None. Use it for checking to see if two objects -- of classes that you designed -- are the same instance. You can't easily use it for strings or numbers because the rules for creation of those built-in classes are complex. Some strings are interned. Some numbers, similarly, are interned.

这篇关于将两个字符串与“is"进行比较——未按预期执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆