Python:如何通过引用传递字符串? [英] Python: How do I pass a string by reference?

查看:45
本文介绍了Python:如何通过引用传递字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自此链接:如何传递变量,我们知道,Python在作为参数传递给函数时会复制一个字符串(一个不可变的类型变量),但是我认为如果字符串很大的话会浪费内存.很多情况下,我们需要用函数来包装一些字符串的操作,所以想知道怎么做更有效?

解决方案

Python 不会复制传递给函数的对象(包括字符串):

<预><代码>>>>定义 foo(s):...返回ID...>>>x = '废话'>>>id(x) == foo(x)真的

如果你需要在函数中修改"一个字符串,返回新的字符串并赋值回原来的名字:

<预><代码>>>>定义栏:... 返回 s + '!'...>>>x = '废话'>>>x = 条(x)>>>X'等等!

不幸的是,当对大字符串进行小的更改时,这可能会非常低效,因为大字符串会被复制.处理这个问题的 Pythonic 方法是将字符串保存在一个列表中,并在您拥有所有部分后将它们连接在一起.

From this link: How do I pass a variable by reference?, we know, Python will copy a string (an immutable type variable) when it is passed to a function as a parameter, but I think it will waste memory if the string is huge. In many cases, we need to use functions to wrap some operations for strings, so I want to know how to do it more effective?

解决方案

Python does not make copies of objects (this includes strings) passed to functions:

>>> def foo(s):
...     return id(s)
...
>>> x = 'blah'
>>> id(x) == foo(x)
True

If you need to "modify" a string in a function, return the new string and assign it back to the original name:

>>> def bar(s):
...     return s + '!'
...
>>> x = 'blah'
>>> x = bar(x)
>>> x
'blah!'

Unfortunately, this can be very inefficient when making small changes to large strings because the large string gets copied. The pythonic way of dealing with this is to hold strings in an list and join them together once you have all the pieces.

这篇关于Python:如何通过引用传递字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆