如何复制 Python 字符串? [英] How can I copy a Python string?

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

问题描述

我这样做:

a = '你好'

现在我只想要一个 a 的独立副本:

导入副本b = str(a)c = a[:]d = a + ''e = copy.copy(a)地图( id, [ a,b,c,d,e ] )

出[3]:

[4365576160, 4365576160, 4365576160, 4365576160, 4365576160]

为什么它们都有相同的内存地址,我怎样才能获得a的副本?

解决方案

您不需要复制 Python 字符串.它们是不可变的,并且 copy 模块在这种情况下总是返回原始值,就像 str() 一样,整个字符串切片,并与空字符串连接.>

此外,您的 'hello' 字符串是 interned (某些字符串是).Python 特意只保留一个副本,因为这样可以加快字典查找速度.

解决此问题的一种方法是实际创建一个新字符串,然后将该字符串切回原始内容:

<预><代码>>>>a = '你好'>>>b = (a + '.')[:-1]>>>身份证件(a),身份证件(b)(4435312528, 4435312432)

但你现在所做的只是浪费内存.毕竟,您似乎无法以任何方式改变这些字符串对象.

如果您只想知道 Python 对象需要多少内存,请使用 sys.getsizeof();它为您提供任何 Python 对象的内存占用.

对于容器,这包括内容;你必须递归到每个容器来计算总内存大小:

<预><代码>>>>导入系统>>>a = '你好'>>>sys.getsizeof(a)42>>>b = {'foo': 'bar'}>>>sys.getsizeof(b)280>>>sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())360

然后,您可以选择使用 id() 跟踪来获取实际内存占用量,或者在对象未被缓存和重用的情况下估计最大占用量.

I do this:

a = 'hello'

And now I just want an independent copy of a:

import copy

b = str(a)
c = a[:]
d = a + ''
e = copy.copy(a)

map( id, [ a,b,c,d,e ] )

Out[3]:

[4365576160, 4365576160, 4365576160, 4365576160, 4365576160]

Why do they all have the same memory address and how can I get a copy of a?

解决方案

You don't need to copy a Python string. They are immutable, and the copy module always returns the original in such cases, as do str(), the whole string slice, and concatenating with an empty string.

Moreover, your 'hello' string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.

One way you could work around this is to actually create a new string, then slice that string back to the original content:

>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)

But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.

If all you wanted to know is how much memory a Python object requires, use sys.getsizeof(); it gives you the memory footprint of any Python object.

For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:

>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360

You can then choose to use id() tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.

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

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