使用函数进行字符串操作(替换和反向)

Re-*_*e-l 0 python function str-replace

所有!

新手在这里!我试图创建一个允许我替换四个字符(ACTG)的函数.为了更简洁,我想用'T'代替'A',用'G'代替'C',反之亦然.

我到目前为止的代码是这样的,但我得到一个错误(翻译预期至少有1个参数,得到0).

#!/usr/bin/python
from sys import argv
from os.path import exists

def translate():
    str.replace("A", "T");
    str.replace("C", "G");
    str.replace("G", "C");
    str.replace("T", "A");

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

in_file = open(from_file)
indata = in_file.read()

newdata = indata.translate()

out_file = open(to_file, 'w')
out_file.write(newdata[::-1])

out_file.close()
in_file.close()
Run Code Online (Sandbox Code Playgroud)

我尝试给translate函数一个argument(def translate(str))并用str(newdata = indata.translate(str))调用它,但那些也没用.

将不胜感激任何帮助和指导.

mar*_*etr 5

使用翻译表:

import string
table = string.maketrans('ACGT', 'TGCA')
Run Code Online (Sandbox Code Playgroud)

您可以像这样应用转换:

with open(from_file) as f:
    contents = f.read()

contents = contents.translate(table)  # Swap A<->T and C<->G
contents = contents[::-1]  # Reverse the string

with open(to_file, 'w') as f:
    f.write(contents)
Run Code Online (Sandbox Code Playgroud)