为什么Python字符串是不可变的?使用它们的最佳实践 [英] Why are Python strings immutable? Best practices for using them

查看:123
本文介绍了为什么Python字符串是不可变的?使用它们的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 使Python字符串不可变的设计原因是什么?它如何使编程变得更容易?
  2. 我习惯于可变字符串,例如C语言中的可变字符串.我应该如何在没有可变字符串的情况下进行编程?有什么最佳做法吗?

推荐答案

当您收到一个字符串时,可以确保它保持不变.假设您将使用字符串参数按如下所示构造Foo,然后修改该字符串;那么Foo的名称将会突然更改:

When you receive a string, you'll be sure that it stays the same. Suppose that you'd construct a Foo as below with a string argument, and would then modify the string; then the Foo's name would suddenly change:

class Foo(object):
    def __init__(self, name):
        self.name = name

name = "Hello"
foo = Foo(name)
name[0] = "J"

使用可变字符串,您必须一直进行复制,以防止发生不良情况.

With mutable strings, you'd have to make copies all the time to prevent bad things from happening.

它还使单个字符与长度为1的字符串没有区别,因此所有字符串运算符也适用于字符.

It also allows the convenience that a single character is no different from a string of length one, so all string operators apply to characters as well.

最后,如果字符串不是不可变的,您将不能可靠地将它们用作dict中的键,因为它们的哈希值可能会突然改变.

And lastly, if strings weren't immutable, you couldn't reliably use them as keys in a dict, since their hash value might suddenly change.

对于使用不可变字符串进行编程,只需习惯像对待数字一样对待它们:作为,而不是作为对象.更改name的首字母为

As for programming with immutable strings, just get used to treating them the same way you treat numbers: as values, not as objects. Changing the first letter of name would be

name = "J" + name[1:]

这篇关于为什么Python字符串是不可变的?使用它们的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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