替换字符串中多个字符的最有效方法 [英] Most Efficient Way to Replace Multiple Characters in a String

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

问题描述

假设有一个任意长度的字符串,它只包含字母 A 到 D:

Let's say there is a string of any length, and it only contains the letters A through D:

s1 = 'ACDCADBCDBABDCBDAACDCADCDAB'

将每个B"替换为C"并将每个C"替换为B"的最有效/最快的方法是什么.

What is the most efficient/fastest way to replace every 'B' with an 'C' and every 'C' with a 'B'.

这是我现在在做什么:

replacedString = ''
for i in s1:
    if i == 'B':
        replacedString += 'C'
    elif i == 'C':
        replacedString += 'B'
    else:
        replacedString += i

这行得通,但显然不是很优雅.问题是我正在处理可能是数百万个字符长的字符串,所以我需要一个更好的解决方案.

This works but it is obviously not very elegant. The probelm is that I am dealing with strings that can be ones of milliions of characters long, so I need a better solution.

我想不出用 .replace() 方法来做到这一点的方法.表明也许正则表达式是要走的路.这也适用于这里吗?如果是这样,什么是合适的正则表达式?有没有更快的方法?

I can't think of a way to do this with the .replace() method. This suggests that maybe a regular expression is the way to go. Is that applicable here as well? If so what is a suitable regular expression? Is there an even faster way?

谢谢.

推荐答案

除了 str.translate 方法,你可以简单地构建一个翻译字典并自己运行.

Apart from the str.translate method, you could simply build a translation dict and run it yourself.

s1 = 'ACDCADBCDBABDCBDAACDCADCDAB'

def str_translate_method(s1):
    try:
        translationdict = str.maketrans("BC","CB")
    except AttributeError: # python2
        import string
        translationdict = string.maketrans("BC","CB")
    result = s1.translate(translationdict)
    return result

def dict_method(s1):
    from, to = "BC", "CB"
    translationdict = dict(zip(from, to))
    result = ' '.join([translationdict.get(c, c) for c in s1])
    return result

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

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