如何在Python中替换字符串中的字符?

时间:2011-12-03 18:51:20

标签: python

我正在尝试找到执行以下操作的最佳方法:

我有一个字符串可以说:

str = "pkm adp"

我在字典中有一些代码来替换每个字符,例如:

code =  {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'}

'a'应由'c'替换,'d'替换为'a' ...)

如何使用字典中的必需字符转换第一个字符串以获取新字符串?例如,我应该将"red car"作为新字符串。

6 个答案:

答案 0 :(得分:8)

试试这个:

>>> import string
>>> code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'}
>>> trans = string.maketrans(*["".join(x) for x in zip(*code.items())])
>>> str = "pkm adp"
>>> str.translate(trans)
'red car'

说明:

>>> help(str.translate)
Help on built-in function translate:

translate(...)
    S.translate(table [,deletechars]) -> string

    Return a copy of the string S, where all characters occurring
    in the optional argument deletechars are removed, and the
    remaining characters have been mapped through the given
    translation table, which must be a string of length 256.

>>> help(string.maketrans)
Help on built-in function maketrans in module strop:

maketrans(...)
    maketrans(frm, to) -> string

    Return a translation table (a string of 256 bytes long)
    suitable for use in string.translate.  The strings frm and to
    must be of the same length.

maketrans行将字典转换为两个独立的字符串,适合输入maketrans

>>> code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'}
>>> code.items()
[('a', 'c'), ('p', 'r'), ('k', 'e'), ('m', 'd'), ('d', 'a')]
>>> zip(*code.items())
[('a', 'p', 'k', 'm', 'd'), ('c', 'r', 'e', 'd', 'a')]
>>> ["".join(x) for x in zip(*code.items())]
['apkmd', 'creda']

答案 1 :(得分:6)

>>> s = "pkm adp"
>>> code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'}
>>> from string import maketrans
>>> s.translate(maketrans(''.join(code.keys()), ''.join(code.values())))
'red car'

答案 2 :(得分:6)

"".join(code.get(k, k) for k in str)

也适用于你的情况。

如果code.get(k, k)code[k]中的有效密钥,则

k会返回code;如果不是,则返回k本身。

答案 3 :(得分:0)

虽然它会很乏味,但快速修复是str.replace(“旧”,“新”)。以下是您的帮助文档http://www.tutorialspoint.com/python/string_replace.htm

答案 4 :(得分:0)

假设您使用的是Python 2.x:

>>> from string import translate, maketrans
>>> data = "pkm adp"
>>> code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'}
>>> table = maketrans(''.join(code.keys()), ''.join(code.values()))
>>> translate(data, table)
'red car'

答案 5 :(得分:0)

>>>print ''.join([code.get(s,s) for s in str])
'red car'