将字符串中的字符替换为另一个python

2024-09-27 21:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有两个DNA样本:

text = "AANGCTWCAAGGT"
text1= "AAGTTTCG"

文本包含不明确的核苷酸“N”和“W”,因为它们不是“AGCT”(注意:任何不是“AGCT”或“AGCT”的核苷酸都被认为是不明确的)
这就是text1的目的,它不包含任何模棱两可的核苷酸,我想比较text1和text1,用text1替换text1中模棱两可的核苷酸。所以‘N’=‘G’和‘W’=‘C’,基于它们的位置。你知道吗

我的代码:

text = "AANGCTWCAAGGT"
text1= "AAGTTTCG"
m = len(text)
n = len(text1)
for j in range(n)[1:]:
if 'A' not in text[j] and 'G' not in text[j]and 'C' not in text[j]and 'T' not in text[j]and 'a' not in text[j]and 'g' not in text[j]and 'c' not in text[j]and 't' not in text[j]:
    newtext = text.replace(text[j], text1[j])
    print(newtext)

输出:

In[89]:runfile('C:/Users/..code')
AAGGCTWCAAGGT
AANGCTCCAAGGT

期望输出:

AAGGCTCCAAGGT

我想我遗漏了什么,也许是另一个循环?我不确定如何修复代码,以便将替换项合并到最终输出中。你知道吗


Tags: and代码textin文本lennotdna
3条回答

怎么样:

text = "AANGCTWCAAGGT"
text1= "AAGTTTCG"

print ''.join(c if c.lower() in 'agct' else text1[i] for i,c in enumerate(text))

>> AAGGCTCCAAGGT

从我在评论和问题中了解到的情况来看,您可能会喜欢这样的东西(与yurib的答案的算法相同,但在一个循环中):

text = "AANGCTWCAAGGT"
text1= "AAGTTTCG"

res = ""
for i,c in enumerate(text):
    if c.lower() in 'agct':
        res = res +c
    else:
        res = res + text1[i]

替换时使用的是文本而不是newtext。所以每当你做替换的时候,newtext都会把它的变化扔掉。每次替换时都需要使用newtext。或者需要允许就地编辑。例如:

text = "AANGCTWCAAGGT"
t_list = [c for c in text]
text1= "AAGTTTCG"
m = len(text)
n = len(text1)
for j in range(1, n):
    if 'A' not in text[j] and 'G' not in text[j]and 'C' not in text[j] and 'T' not in text[j] and 'a' not in text[j]and 'g' not in text[j]and 'c' not in text[j]and 't' not in text[j]:
        t_list[j] = text1[j]

print("".join(t_list))

相关问题 更多 >

    热门问题