2 つの文字列をisで比較しようとしています。1 つの文字列は関数によって返され、もう 1 つの文字列は比較で宣言されているだけです。はオブジェクト ID のテストですが、このページによると、Python のメモリ最適化により、2 つの同一の文字列でも機能します。ただし、次の場合は機能しません。
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'
出力:
「str」と入力します ユーザー 失敗した わかった
これの理由は、関数によって返される文字列が文字列リテラルとは異なる「タイプ」の文字列であるためだと思います。文字列リテラルを返す関数を取得する方法はありますか? ==を使用できることはわかっていますが、ただ興味があります。