Python: How do I pass a string by reference?

前端 未结 7 1082
清歌不尽
清歌不尽 2020-12-05 18:21

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

7条回答
  •  猫巷女王i
    2020-12-05 18:51

    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.

提交回复
热议问题