何时以及为何在 Python 中使用 [:] [英] When and why to use [:] in python
问题描述
sentence = "你好"打印句子打印句子[:]
两者输出相同的东西,即Hello
那么,何时以及为什么使用/不使用 [:]
?
谢谢!:)
正如 Nobi 在评论中指出的那样,有已经是一个 关于 Python 的切片符号的问题.正如对该问题的回答所述,没有开始和结束值 ([:]
) 的切片基本上创建了原始序列的副本.
但是,您遇到了字符串的特殊情况.由于字符串是不可变的,因此创建字符串的副本是没有意义的.由于您将无法修改字符串的任何实例,因此无需在内存中拥有多个实例.所以,基本上,使用 s[:]
(作为 s
一个字符串)你不是在创建字符串的副本;该语句返回与 s
引用的字符串完全相同的字符串.一个简单的方法是使用 id()
(对象标识)函数:
身份不同.但是,使用字符串:
<预><代码>>>>s1 = "你好">>>s2 = s1[:]>>>id(s1)3072585984L>>>id(s2)3072585984L身份是相同的,这意味着两者是完全相同的对象.
sentence = "Hello"
print sentence
print sentence[:]
Both outputs the same thing, i.e. Hello
So, when and why to use/not use [:]
?
Thanks! :)
As Nobi pointed out in the comments, there's already a question regarding Python's slicing notation. As stated in the answer to that question, the slicing without start and end values ([:]
) basically creates a copy of the original sequence.
However, you have hit a special case with strings. Since strings are immutable, it makes no sense to create a copy of a string. Since you won't be able to modify any instance of the string, there's no need to have more than one in memory. So, basically, with s[:]
(being s
a string) you're not creating a copy of the string; that statement is returning the very same string referenced by s
. An easy way to see this is by using the id()
(object identity) function:
>>> l1 = [1, 2, 3]
>>> l2 = l1[:]
>>> id(l1)
3075103852L
>>> id(l2)
3072580172L
Identities are different. However, with strings:
>>> s1 = "Hello"
>>> s2 = s1[:]
>>> id(s1)
3072585984L
>>> id(s2)
3072585984L
Identity is the same, meaning both are the same exact object.
这篇关于何时以及为何在 Python 中使用 [:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!