如何更改知道它在 Python 中位置的字符串中的字母?

How do I change letter in string knowing it position in Python?

我有这个问题,在编写遗传算法时,当我尝试模拟变异过程时: 1.所以我选择随机position = randint(0, len(genes)-1)
其中基因的格式为“10101”,1 和 0 是随机设置的 2. 我尝试用 0 或 1 替换 1 或 0 来模拟突变然后我得到了很多错误。

我这样试过:

position = randint(0, len(genes)-1)
if(genes[position]=="1"): 
    genes[position] = "0"
if(genes[position]=="0"): 
    genes[position] = "1"

那是行不通的。 我也试过:

if(genes[position_to_mutate]=="1"):
genes_new = ""
    if(position_to_mutate == 0):
        genes_new = "0" + genes[1:len(genes)]
        print "genes z zerowym nowym : ", genes
    if(position_to_mutate!=0):
        genes_new = genes[0:position_to_mutate] + "0" + genes[position_to_mutate+1:len(genes)]
    if(position_to_mutate==4):
        genes_new = genes[0:len(genes)-2] + "0" 

那么,如何根据字符串中的位置将一个符号替换为另一个符号?

python 中的字符串是不变的。

所以需要新建实例进行修改

或者您可以为此目的使用 list,并在修改后将其转换回 str

>>> mystr = '1001'
>>> tmp = list(mystr)
>>> tmp[0] = '0'
>>> mystr = ''.join(tmp)
>>> mystr
'0001'

正如我评论的那样,字符串是不可变的,因此您不能使用赋值,您可以将字符串存储在 bytearray 中并对其进行变异,然后只需调用字节数组上的 str 即可从字节数组中获取新字符串,当您完成变异:

In [42]: s = "10101"

In [43]: b_s = bytearray(s)

In [44]: b_s[0] = "0"

In [45]: str(b_s)
Out[45]: '00101'

In [46]: b_s[0:2] = "11"

In [47]: str(b_s)
Out[47]: '11101'

如果您进行所有更改然后取回您的字符串,而不是不断创建新字符串,效率会高很多。

字符串是不可变的,你需要重新赋值,你可以这样做:

genes = "101010101"
position = randint(0, len(genes)-1)
new_val = "1" if genes[position] == "0" else "0"
genes = genes[:position] + new_val + genes[position+1:]

正如其他人所指出的,字符串是不可变的。但是,您可以使用切片运算符的优点来缩短您的版本:

genes_new = genes[:p] + "0" + genes[p+1:]

# another way is to use this kind of generator expression
''.join(x[i] if i != p else '0' for i in xrange(len(x)))