#๐Ÿ”’ Replace characters

50 messages ยท Page 1 of 1 (latest)

cyan trout
#

Hello!

I'm relatively new to python and only know functions and simple math. I decided I want to make a code that can write give complementary DNA strand as an output. I've managed to flip the strand but I need to replace the letters.
The issue is that I need to replace the original "T" with "A" and "A" with "T" (same for "G" and "C) but if I do .replace() it makes it so that all "A"s become "T"s. Does anyone know how to fix this issue?

Thanks in advance!

zenith summitBOT
#

@cyan trout

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

cyan trout
#

Here's what I mean (ignore the RNA part).

#

Wait I just realized I deleted the 2nd .replace in the photo lol.

modest kite
#

Basicly you want to transpose each character on its own. As you've discovered a .replace() does the whole string, and afterwards eg you don't know if an "A" is an "A" which should be switchs (an original "A") or an "A" which should be left alone (an "A" from the replacement of a "T").
The simple thing is probably to iterate over the string and replace on a per character basis, eg:

chars = []
for char in DNA:
    if char == "A":
        char = "T"
    elif char == "T":
        char = "A"
    ... and so on ...
    chars.append(char)
# now we have a list of 1 character strings
DNA2 = ''.join(chars) # join them together into one string
#

@cyan trout ^^

cyan trout
#

Iโ€™ll test it in a sec, thank you very much!

crude niche
#

!e - this is not beginner material, but damn it's nice so i just had to demo it

dna = "ATGCCGTA"
flipper = str.maketrans("ATCG", "TAGC")
complementary_dna = dna.translate(flipper)
print(complementary_dna)
zenith summitBOT
crude niche
cyan trout
#

Oh wow!

crude niche
#

!d str.maketrans

zenith summitBOT
#

static str.maketrans(dict, /)``````py

static str.maketrans(from, to, remove='', /)```
This static method returns a translation table usable for [`str.translate()`](https://docs.python.org/3/library/stdtypes.html#str.translate).

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or `None`. Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in *from* will be mapped to the character at the same position in *to*. If there is a third argument, it must be a string, whose characters will be mapped to `None` in the result.
cyan trout
crude niche
#

it makes a translation table where it maps the first letter in the first string to the first letter in the second string and so on

crude niche
#

!d str.translate

zenith summitBOT
#

str.translate(table, /)```
Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via [`__getitem__()`](https://docs.python.org/3/reference/datamodel.html#object.__getitem__), typically a [mapping](https://docs.python.org/3/glossary.html#term-mapping) or [sequence](https://docs.python.org/3/glossary.html#term-sequence). When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return `None`, to delete the character from the return string; or raise a [`LookupError`](https://docs.python.org/3/library/exceptions.html#LookupError) exception, to map the character to itself.

You can use [`str.maketrans()`](https://docs.python.org/3/library/stdtypes.html#str.maketrans) to create a translation map from character-to-character mappings in different formats.

See also the [`codecs`](https://docs.python.org/3/library/codecs.html#module-codecs) module for a more flexible approach to custom character mappings.
crude niche
cyan trout
crude niche
#

the .translate() string method uses the translation table that we prepared before with str.maketrans() and saved to the variable filpper

crude niche
#

should it be in the reverse order too?

cyan trout
#

Ye, just the [::-1] thingy

#

Usually we write things from 5' so to do that the string has to be flipped

crude niche
#

from 5' ?
i don't know what that means

cyan trout
#

Like this

crude niche
#

okay, i still don't really see why one would do that, but that's not important ๐Ÿ˜…

#

anyways, see if we can figure out what's going wrong with your code there

cyan trout
#

TYSM!

crude niche
#

!e

def complementary_strand(dna: str) -> str:
    flipper = str.maketrans("ATCG", "TAGC")
    return dna.translate(flipper)[::-1]

dna = "ATGATCTCGTAA"
print(complementary_strand(dna))
zenith summitBOT
crude niche
#

there, all in one small function

cyan trout
#

Very nice!

crude niche
#

i added type hinting to the function as well, just because it's nice to have as well

cyan trout
#

Is it the (: str) -> str: part?

#

I'm very new haha!

crude niche
#

yeah, the first one after the parameter named dna says that this parameter suppose to be of type str (a string) and the one outside and after the parentheses and the -> says that the return type of the function suppose to be of type str (so, also a string)

#

in python we usually use all lowercase letters for normal variables and function names and underscore to separate words, it's affectionately called snake_case

#

while classes are typically named using TitleCase

cyan trout
cyan trout
#

It was fun talking to you! Thank you for all of the advice! I have to go to bed now.

zenith summitBOT
#
Python help channel closed using Discord native close action

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.