2021年3月25日星期四

How to iteratively replace a char in a string?

This should be a really simple problem, but I am stuck. I want to iteratively replace each character in the string "PEPTIDE" with "A" to result in: "AEPTIDE", "PAPTIDE", "PEATIDE", etc. I know that strings are immutable in python, so I first convert the string to a list, then set a counter from 0 to len(str) and then replace the ith char with "A" and join the string back together. For some reason my code is not iteratively replacing A's, but rather just adding A's at each position:

pepSeq = list("PEPTIDE")  x = range(len(pepSeq))      for i in x:      pepSeq2 = pepSeq      pepSeq2[i] = 'A'      print("".join(pepSeq2))  

Result: AEPTIDE AAPTIDE AAATIDE AAAAIDE AAAAADE AAAAAAE AAAAAAA

Any suggestions? It seems that the problem is occuring with my attempt to make a new variable pepSeq2 in an attempt to avoid replacing all chars in pepSeq with A.

https://stackoverflow.com/questions/66809639/how-to-iteratively-replace-a-char-in-a-string March 26, 2021 at 09:03AM

没有评论:

发表评论