【问题标题】:Why can't we change a particular value of a string in python [duplicate]为什么我们不能在python中更改字符串的特定值[重复]
【发布时间】:2018-06-28 08:31:54
【问题描述】:

python 中的字符串的行为类似于 list。那为什么我们不能使用赋值运算符来改变值。

例子:

name = 'whatever'

为什么我们不能像name[0] = 'k' 那样做作业

如果我们需要进行这样的更改,我们该怎么做?

【问题讨论】:

  • 因为字符串是不可变的,你需要像name = 'k' + name[1:]一样重建字符串,但如果你想要一个可变结构,请使用列表

标签: python string


【解决方案1】:

你可以这样做:

s = "abcde"     # create string
l = list(s)     # convert to list
l[2] = "X"      # modify character
"".join(l)      # join to string again

【讨论】:

    【解决方案2】:

    Python 中的字符串是不可变的。您可以使用 .replace() 之类的方法或遍历字符串并创建一个新字符串。

    例如:

    name = 'whatever'
    name.replace("w", "k")
    

    【讨论】:

    • 请在您的答案中添加示例以显示预期用途
    • 我为 .replace() 添加了一个示例。我把这个问题理解为一个更笼统的问题。我认为答案是字符串的不变性..?
    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 2016-08-18
    • 2017-08-04
    • 1970-01-01
    • 2021-08-12
    • 2016-07-12
    相关资源
    最近更新 更多