[英]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
的字符串开头N=0
,那就是
x="G"
Then if I have a range N
, that is 1 , I want to replace G
from x with SRGRS
, so that 然后,如果我有一个范围N
,即1,我想用SRGRS
替换x中的G
,这样
x1="SRGRS"
Then if N=2, I want to replace S
in x1
with GLSLG
and G
with SRGRS
, so that I get 然后如果N = 2,我想将x1
S
替换为GLSLG
,将G
替换为SRGRS
,这样我得到
x2="GLSLGRSRGRSRGLSLG"
and then continue with N+=1, I'm replacing "G" and "S" from x2 with the corresponding string.. 然后继续N + = 1,我将x2中的“ G”和“ S”替换为相应的字符串。
how do I write a loop, that does this continuously? 我该如何编写一个循环,连续进行?
I've tried to use str.replace()
, but I can't it to work :( 我试过使用str.replace()
,但我不能正常工作:(
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" 编辑:在循环中:如果字符串中有“ G”,则应将其替换为“ SRGRS”如果字符串中有“ S”,则应将其替换为“ GLSLG”
For nbIter
iterations, replaces simultaneously "S" by "GLSLG" and "G" by "SRGRS". 对于nbIter
迭代,同时将“ S”替换为“ GLSLG”,将“ G”替换为“ 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.