用 str 方法替换字符串中的多个元素 [英] Replace multiple elements in string with str methods

查看:53
本文介绍了用 str 方法替换字符串中的多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数接受一串 DNA 并返回恭维.我已经尝试解决这个问题一段时间了,并查看了 Python 文档,但无法解决.我已经为函数编写了文档字符串,因此您可以看到答案应该是什么样子.我在这个论坛上看到过类似的问题,但我无法理解答案.如果有人可以仅使用 str 格式和循环/if 语句来解释这一点,我将不胜感激,因为我还没有详细研究字典/列表.

我尝试了 str.replace 但无法让它适用于多个元素,尝试嵌套 if 语句,但这也不起作用.然后我尝试编写 4 个单独的 for 循环,但无济于事.

def get_complementary_sequence(dna):""" (str) -> str返回互补的 DNA 序列到给定的 DNA 序列.>>>get_complementary_sequence('AT')助教>>>get_complementary_sequence('GCTTAA')贸促会"""对于 dna 中的字符:如果字符 == A:dna = dna.replace('A', 'T')elif 字符 == T:dna = dna.replace('T', 'A')# ...等等

解决方案

您可以将每个字母映射到另一个字母.

您可能不需要创建所有可能组合的翻译表.

<预><代码>>>>M = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}>>>STR = 'CGAATT'>>>S = "".join([M.get(c,c) for c in STR])>>>秒'GCTTAA'

这是如何工作的:

# 这将根据您的 dict M 返回一个字符列表>>>L = [M.get(c,c) for c STR]>>>升['G', 'C', 'T', 'T', 'A', 'A']

join() 方法返回一个字符串,其中序列的字符串元素已由 str 分隔符连接.

<预><代码>>>>str = "-">>>L = ['a','b','c']>>>str.join(L)'a-b-c'

I am trying to write a function that takes a string of DNA and returns the compliment. I have been trying to solve this for a while now and looked through the Python documentation but couldn't work it out. I have written the docstring for the function so you can see what the answer should look like. I have seen a similar question asked on this forum but I could not understand the answers. I would be grateful if someone can explain this using only str formatting and loops / if statements, as I have not yet studied dictionaries/lists in detail.

I tried str.replace but could not get it to work for multiple elements, tried nested if statements and this didn't work either. I then tried writing 4 separate for loops, but to no avail.

def get_complementary_sequence(dna):

    """ (str) -> str

    Return the DNA sequence that is complementary 
    to the given DNA sequence.

    >>> get_complementary_sequence('AT')
    TA
    >>> get_complementary_sequence('GCTTAA')
    CGAATT

    """

    for char in dna:
        if char == A:
            dna = dna.replace('A', 'T')
        elif  char == T:
            dna = dna.replace('T', 'A')
        # ...and so on

解决方案

You can map each letter to another letter.

You probably need not create translation table with all possible combination.

>>> M = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
>>> STR = 'CGAATT'
>>> S = "".join([M.get(c,c) for c in STR])
>>> S
'GCTTAA'

How this works:

# this returns a list of char according to your dict M
>>> L = [M.get(c,c) for c in STR]  
>>> L
['G', 'C', 'T', 'T', 'A', 'A']

The method join() returns a string in which the string elements of sequence have been joined by str separator.

>>> str = "-"
>>> L = ['a','b','c']
>>> str.join(L)
'a-b-c'

这篇关于用 str 方法替换字符串中的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆