为什么 Python 中不推荐使用 MutableString?
为什么 Python 2.6 中不推荐使用 MutableString 类;
为什么它在 Python 3 中被删除了?
Why was the MutableString class deprecated in Python 2.6;
and why was it removed in Python 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MutableString
类的目的是为了教育目的,而不是在实际程序中使用。如果您查看实现,您会发现您无法在需要可变字符串的严肃应用程序中真正使用它。如果您需要可变字节字符串,您可以考虑使用 Python 2.6 和 3.x 中提供的
bytearray
。每次修改旧字符串时,该实现都不会创建新字符串,因此它更快、更可用。它还正确支持缓冲区协议,因此几乎可以在任何地方使用它来代替普通字节串。如果您真的不打算通过索引对单个字符串进行多次修改,那么通过创建新字符串来修改普通字符串应该适合您(例如通过
str.replace
、str.格式
和re.sub
)。没有可变的 unicode 字符串,因为这被认为是不常见的应用程序,但您始终可以实现
__unicode__
(或 Python 3 的__str__
)和encode
自定义序列类型上的方法来模拟一种。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
andre.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) andencode
methods on your custom sequence type to emulate one.我猜是因为字符串不应该是可变的。毕竟,主要目的是“教育”。如果需要更改字符串,请使用字符串列表或 StringIO。
I'm guessing because strings aren't supposed to be mutable. The primary purpose was "educational", after all. If you need to mutate strings, use a list of strings or StringIO.