为什么在Python中不推荐使用MutableString? [英] Why is MutableString deprecated in Python?

查看:193
本文介绍了为什么在Python中不推荐使用MutableString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在Python 2.6中不推荐使用 MutableString 类;
为何在Python 3中将其删除?

解决方案

MutableString类的目的是为了教育,而不是在实际程序中使用.如果看一下实现,您会发现您不能在需要可变字符串的严肃应用程序中真正使用它.

如果需要可变的字节串,则可以考虑使用Python 2.6和3.x中可用的bytearray.该实现不会在您每次修改旧字符串时都创建新字符串,因此它更快,更实用.它还正确支持缓冲区协议,因此几乎可以在任何地方使用它代替常规字节串.

如果您真的不想按索引对单个字符串进行很多修改,那么通过创建一个新字符串来修改普通字符串应该适合您(例如,通过str.replacestr.formatre.sub).

没有可变的unicode字符串,因为这被认为是不常见的应用程序,但是您始终可以在自定义序列类型上实现__unicode__(对于Python 3为__str__)和encode方法来模拟一个. /p>

Why was the MutableString class deprecated in Python 2.6;
and why was it removed in Python 3?

解决方案

The MutableString class was meant to be educational, and not to be used in real programs. If you look at the implementation, you'd see that you can't really use this in a serious application requiring mutable strings.

If you need mutable bytestrings, you might consider using bytearray that's available in Python 2.6 and 3.x. The implementation doesn't create new strings every time you modify the old one, so it is much more faster and usable. It also supports the buffer protocol properly so it can be used in place of a normal bytestring practically everywhere.

If you aren't really going to do many modifications of a single string by index, modifying a normal string by creating a new one should suit you (for example through str.replace, str.format and re.sub).

There are no mutable unicode strings, because this is considered an uncommon application, but you can always implement __unicode__ (or __str__ for Python 3) and encode methods on your custom sequence type to emulate one.

这篇关于为什么在Python中不推荐使用MutableString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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