F.Kncja
F.Kncja

Reputation: 41

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

I have this problem, while writting genetic algorithm, when I try to simulate mutation process: 1. so I choose random position = randint(0, len(genes)-1)
where genes are in format "10101" and 1s and 0s are set randomly 2. I try to replace 1 or 0 with 0 or 1 to simulate mutation then I got many errors.

I tried this way:

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

That does not work. I tried also with:

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" 

So, how do I replace one sign with the other getting it by its position in the string?

Upvotes: 1

Views: 119

Answers (4)

David Zemens
David Zemens

Reputation: 53623

Strings are immutable, you need to reassign and you can do something like this:

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:]

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

As I commented strings are immutable so you cannot use assignment, you could store the string in a bytearray and mutate that then just call str on the bytearray to get the new string back from the bytearray when you are finished mutating:

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'

It is going to be a lot more efficient if you make all the changes and then get your string back as opposed to continually creating new strings.

Upvotes: 0

user2390182
user2390182

Reputation: 73460

As others have pointed out, strings are immutable. However, you can shorten your version using the niceties of the slice operator:

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)))

Upvotes: 0

xiº
xiº

Reputation: 4687

strings in python are immutabe.

So you need to create new instance for modification.

Or you could use list for that purpose and after modifications convert it back to str.

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

Upvotes: 1

Related Questions