Ste*_*rst 25 python python-3.x
我正在学习python,我将通过https://developers.google.com/edu/python/strings上的教程
在" 字符串切片"部分下
s [:]是'Hello' - 省略两者总是给我们一个整体的副本(这是复制像字符串或列表的序列的pythonic方式)
出于好奇,你为什么不使用=运营商呢?
s = 'hello';
bar = s[:]
foo = s
Run Code Online (Sandbox Code Playgroud)
至于我可以告诉双方bar,并foo具有相同的值.
Tho*_*anz 41
=通过使用[:]您创建副本来引用.对于不可变的字符串,这并不重要,但对于列表等,这是至关重要的.
>>> s = 'hello'
>>> t1 = s
>>> t2 = s[:]
>>> print s, t1, t2
hello hello hello
>>> s = 'good bye'
>>> print s, t1, t2
good bye hello hello
Run Code Online (Sandbox Code Playgroud)
但:
>>> li1 = [1,2]
>>> li = [1,2]
>>> li1 = li
>>> li2 = li[:]
>>> print li, li1, li2
[1, 2] [1, 2] [1, 2]
>>> li[0] = 0
>>> print li, li1, li2
[0, 2] [0, 2] [1, 2]
Run Code Online (Sandbox Code Playgroud)
那么为什么在处理字符串时使用它呢?内置字符串是不可变的,但是每当你编写一个期望字符串的库函数时,用户可能会给你"看起来像字符串"和"表现得像字符串"的东西,但它是一种自定义类型.这种类型可能是可变的,因此最好照顾它.
这样的类型可能如下所示:
class MutableString(object):
def __init__(self, s):
self._characters = [c for c in s]
def __str__(self):
return "".join(self._characters)
def __repr__(self):
return "MutableString(\"%s\")" % str(self)
def __getattr__(self, name):
return str(self).__getattribute__(name)
def __len__(self):
return len(self._characters)
def __getitem__(self, index):
return self._characters[index]
def __setitem__(self, index, value):
self._characters[index] = value
def __getslice__(self, start, end=-1, stride=1):
return str(self)[start:end:stride]
if __name__ == "__main__":
m = MutableString("Hello")
print m
print len(m)
print m.find("o")
print m.find("x")
print m.replace("e", "a") #translate to german ;-)
print m
print m[3]
m[1] = "a"
print m
print m[:]
copy1 = m
copy2 = m[:]
print m, copy1, copy2
m[1] = "X"
print m, copy1, copy2
Run Code Online (Sandbox Code Playgroud)
免责声明:这只是一个展示它如何运作和激励使用的样本[:].它是未经测试的,不完整的,可能性能非常高
| 归档时间: |
|
| 查看次数: |
1479 次 |
| 最近记录: |