Replace multiple elements in string with str methods

后端 未结 2 651
清歌不尽
清歌不尽 2021-01-07 14:04

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 documen

相关标签:
2条回答
  • 2021-01-07 14:44

    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'
    
    0 讨论(0)
  • 2021-01-07 14:57

    For a problem like this, you can use string.maketrans (str.maketrans in Python 3) combined with str.translate:

    import string
    table = string.maketrans('CGAT', 'GCTA')
    print 'GCTTAA'.translate(table)
    # outputs CGAATT
    
    0 讨论(0)
提交回复
热议问题