替换字符的 Pythonic 方法 [英] Pythonic way to replace chars

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

问题描述

我想使用 pythonic 方法替换字符串中的一些字符.

A ->吨C->GG->CT->一个

示例:

<块引用>

AAATCGATTGAT

会变成

<块引用>

TTTAGCTAACTA

我做了什么:

def 交换(字符串):string = re.sub('A', 'aux', string)string = re.sub('T', 'A', 字符串)string = re.sub('aux', 'T', string)string = re.sub('C', 'aux', string)string = re.sub('G', 'C', 字符串)string = re.sub('aux', 'G', string)返回字符串

效果很好,但我正在寻找一种更 Pythonic 的方式来实现这一点.

解决方案

这是对 当前接受的 Chepner 删除的 答案的重构,该答案仅调用 maketrans 一次.

tt = str.maketrans({A":T",C":G",G":C",T":;A"})对于AGACAT"、TAGGAC"、ACTAGAA"中的 s1:打印(s1.translate(tt))

也许还指出,您可以将 replace 的结果链接起来,尽管这仍然很笨拙且效率低下:

def acgtgca(s1):返回 s1.replace(A", ue0fa").replace(G", ue0fb").replace(C", G").replace(T", A").replace(ue0fb", C").replace(ue0fa",T")

这避免了使用aux"作为支持 Unicode 私人使用区域中的两个任意字符的特殊标记.>

但同样,maketrans 方法既简洁又高效.

I want to replace some characters in a string using a pythonic approach.

A -> T
C -> G
G -> C
T -> A

Example:

AAATCGATTGAT

will transform into

TTTAGCTAACTA

What I did:

def swap(string):
    string = re.sub('A', 'aux', string)
    string = re.sub('T', 'A', string)
    string = re.sub('aux', 'T', string)
    string = re.sub('C', 'aux', string)
    string = re.sub('G', 'C', string)
    string = re.sub('aux', 'G', string)

    return string

It worked great, but i'm looking for a more pythonic way to reach that.

解决方案

Here's a refactoring of the currently accepted- Chepner's deleted answer which only calls maketrans once.

tt = str.maketrans({"A":"T", "C":"G", "G":"C", "T": "A"})
for s1 in "AGACAT", "TAGGAC", "ACTAGAA":
    print(s1.translate(tt))

Perhaps also point out that you can chain the result from replace, though this is still clumsy and inefficient:

def acgtgca(s1):
    return s1.replace(
        "A", "ue0fa").replace(
        "G", "ue0fb").replace(
        "C", "G").replace(
        "T", "A").replace(
        "ue0fb", "C").replace(
        "ue0fa", "T")

This avoids using "aux" as a special marker in favor of two arbitrary characters out of the Unicode Private Use Area.

But again, the maketrans method is both neater and more efficient.

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

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