Python函数修改字符串 [英] Python function to modify string
问题描述
有一次我被要求创建一个函数,给定一个字符串,从字符串中删除几个字符.
是否可以在 Python 中执行此操作?
这可以用于列表,例如:
def poplist(l):l.pop()l1 = ['a', 'b', 'c', 'd']弹出列表(l1)打印 l1>>>['a', 'b', 'c']
我想要的是为字符串做这个函数.我能想到的唯一方法是将字符串转换为列表,删除字符,然后将其连接回字符串.但那时我将不得不返回结果.例如:
def 弹出字符串:副本 = 列表副本.pop()s = ''.join(复制)s1 = 'abcd'弹出字符串(s1)打印 s1>>>'A B C D'
我明白为什么这个功能不起作用.问题更多的是是否可以在 Python 中执行此操作?如果是,我可以不复制字符串吗?
字符串不可变,这意味着你不能改变str
对象.您当然可以构造一个新字符串,该字符串是对旧字符串的一些修改.但是你不能因此改变代码中的 s
对象.
一种解决方法可能是使用容器:
类容器:def __init__(self,data):self.data = 数据
然后 popstring
被赋予一个包含,它检查容器,并将其他东西放入其中:
def 弹出字符串(容器):容器.数据 = 容器.数据[:-1]s1 = 容器('abcd')弹出字符串(s1)
但同样:您没有更改字符串对象本身,您只是将一个新字符串放入容器中.
您不能在 Python 中执行按引用调用,所以你不能调用一个函数:
foo(x)
然后修改变量x
:x
的引用被复制,所以你不能修改变量x
本身.>
I was asked once to create a function that given a string, remove a few characters from the string.
Is it possible to do this in Python?
This can be done for lists, for example:
def poplist(l):
l.pop()
l1 = ['a', 'b', 'c', 'd']
poplist(l1)
print l1
>>> ['a', 'b', 'c']
What I want is to do this function for strings. The only way I can think of doing this is to convert the string to a list, remove the characters and then join it back to a string. But then I would have to return the result. For example:
def popstring(s):
copys = list(s)
copys.pop()
s = ''.join(copys)
s1 = 'abcd'
popstring(s1)
print s1
>>> 'abcd'
I understand why this function doesn't work. The question is more if it is possible to do this in Python or not? If it is, can I do it without copying the string?
Strings are immutable, that means you can not alter the str
object. You can of course construct a new string that is some modification of the old string. But you can thus not alter the s
object in your code.
A workaround could be to use a container:
class Container:
def __init__(self,data):
self.data = data
And then the popstring
thus is given a contain, it inspect the container, and puts something else into it:
def popstring(container):
container.data = container.data[:-1]
s1 = Container('abcd')
popstring(s1)
But again: you did not change the string object itself, you only have put a new string into the container.
You can not perform call by reference in Python, so you can not call a function:
foo(x)
and then alter the variable x
: the reference of x
is copied, so you can not alter the variable x
itself.
这篇关于Python函数修改字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!