【问题标题】:How do I assign a character variable to a poistion in the string varible in python? [duplicate]如何将字符变量分配给python中字符串变量中的位置? [复制]
【发布时间】:2017-07-16 11:55:24
【问题描述】:

我现在正在使用 Python。

我的 ch 变量,即字符变量,里面有一个字符存储,它是用户输入的。 我还有一个字符串变量(string1),我想在其中添加字符而不覆盖字符串变量。

即我想做string1[i]=ch,其中i可以是任意位置。

当我在 python 中执行此操作时,它会给出错误消息:'str' object does not support item assignment。

这里,string1[i]=ch,在一个 while 循环中。

有没有合适的方法来做到这一点?请帮忙。

【问题讨论】:

  • 如果您不告诉我们您基本上希望实现什么或不查看您的代码,就不可能为您提供帮助

标签: python string variables character


【解决方案1】:

str 在 python 中是不可变的。这意味着,您不能为特定索引分配一些随机值。

例如,以下是不可能的:

a = 'hello'
a[2]= 'X'

有一个解决方法。

  • 从字符串列一个列表。
  • 从该列表中更改您想要的特定索引。
  • 再次从列表中形成一个str。

如下:

>>> a = 'hello'
>>> tmp_list = list(a)
>>> tmp_list
['h', 'e', 'l', 'l', 'o']
>>> tmp_list[2] = 'X'
>>> tmp_list
['h', 'e', 'X', 'l', 'o']
>>> 
>>> a = ''.join(tmp_list)
>>> a
'heXlo'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2020-10-08
    • 2019-08-19
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多