简体   繁体   中英

Replacing Characters in String: first one character replaces with string then another character with another string

If i start with a string called x for N=0 , that is

x="G"

Then if I have a range N , that is 1 , I want to replace G from x with SRGRS , so that

x1="SRGRS"

Then if N=2, I want to replace S in x1 with GLSLG and G with SRGRS , so that I get

x2="GLSLGRSRGRSRGLSLG"

and then continue with N+=1, I'm replacing "G" and "S" from x2 with the corresponding string..

how do I write a loop, that does this continuously?

I've tried to use str.replace() , but I can't it to work :(

edit: in the loop: If there is "G"in the string, it should be replaced with "SRGRS" If there is "S" in the string, it should be replaced with "GLSLG"

For nbIter iterations, replaces simultaneously "S" by "GLSLG" and "G" by "SRGRS".

nbIter=4
x="G"
print(x)

for i in range(nbIter):
    newX=""
    for char in x:
        if char=="S":
            newX+="GLSLG"
        elif char=="G":
            newX+="SRGRS"
        else:
            newX+=char
    x=newX
    print(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM