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

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

问题描述

你好,我正在学习用python编程。我想写一个函数,需要一串DNA并返回赞美,我一直试图解决这一段时间,并通过python文档看,但无法工作出来。我已经写了函数的文档字符串,所以你可以看到答案应该是什么样子。我在这个论坛上看到过类似的问题,但我无法理解答案。如果有人能用str格式和循环/ if语句解释这个问题,我将不胜感激,因为我还没有详细研究字典/列表。提前感谢您

我尝试了str.replace,但无法让它为多个元素工作,试图嵌套if语句,这也没有工作。然后我试着写4个单独的循环,但无济于事。

  def get_complementary_sequence(dna):




















; 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')
#...等等




您可能不需要创建具有所有可能组合的翻译表格。 / p>

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

这是如何工作的:

 #这将根据你的字典返回一个char列表M 
>>> L = [M.get(c,c)对于c中的STR]
>>> L
['G','C','T','T','A','A']

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

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


Hello I am learning to program with python. 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 doc string 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. thank you in advance

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'

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

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