kla*_*aus 2 python string python-2.7
有一次我被要求创建一个给定字符串的函数,从字符串中删除几个字符。
可以在 Python 中做到这一点吗?
这可以为列表完成,例如:
def poplist(l):
l.pop()
l1 = ['a', 'b', 'c', 'd']
poplist(l1)
print l1
>>> ['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)
我想要的是为字符串做这个函数。我能想到的唯一方法是将字符串转换为列表,删除字符,然后将其连接回字符串。但那时我将不得不返回结果。例如:
def popstring(s):
copys = list(s)
copys.pop()
s = ''.join(copys)
s1 = 'abcd'
popstring(s1)
print s1
>>> 'abcd'
Run Code Online (Sandbox Code Playgroud)
我明白为什么这个功能不起作用。问题更多的是是否可以在 Python 中执行此操作?如果是,我可以在不复制字符串的情况下进行吗?
字符串是不可变的,这意味着您不能更改str对象。您当然可以构造一个新字符串,该字符串是对旧字符串的一些修改。但是您因此无法更改s代码中的对象。
解决方法可能是使用容器:
class Container:
def __init__(self,data):
self.data = data
Run Code Online (Sandbox Code Playgroud)
然后popstring给了一个容器,它检查容器,并将其他东西放入其中:
def popstring(container):
container.data = container.data[:-1]
s1 = Container('abcd')
popstring(s1)
Run Code Online (Sandbox Code Playgroud)
但同样:您没有更改字符串对象本身,您只是将一个新字符串放入容器中。
foo(x)
Run Code Online (Sandbox Code Playgroud)
然后改变变量x: 的引用x被复制,所以你不能改变变量x本身。