0
点赞
收藏
分享

微信扫一扫

python中的字符串对象行为

westfallon 2022-01-10 阅读 76

python中的字符串对象行为

很好奇知道关注的原因

x='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' 
y='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
x is y
#output : True
x='a'*21 
y='a'*21
x is y
#output : False

Q1:由于对字符串文字进行了字符串实习,那么为什么不对'a'* 21进行呢?它不是字符串文字吗? 问题2:是因为表达式'a'* 21在运行时求值,而求值是在运行时完成的?

s1 = "strin"
s2 = "string"
s1+"g" is s2

# output : False 
# Explaination : Above code involves a run-time concatenation, the result of which is not automatically interned

Q3: How to know if an expression is going to be evaluated at run-time or compile time? 

最佳答案:

1 个答案:

答案 0 :(得分:0)

如果两个变量指向同一对象,则

is将返回True;如果变量所引用的对象相等,则==将返回True。强>。如果您尝试:

s1 = "strin"
s2 = "string"
s1+"g" == s2
# True

x='a'*21 
y='a'*21
x == y
True

在您的第一种情况下,Python足够聪明,可以使用一个对象来引用您描述两次的文字字符串。通常情况并非如此。

Tags:python string 

举报

相关推荐

0 条评论