简体   繁体   English

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

[英]How do I replace characters in a string in Python?

I'm trying to find the best way to do the following: 我正在尝试找到执行以下操作的最佳方法:

I have a string lets say: 我有一个字符串让我们说:

str = "pkm adp"

and I have a certain code in a dictionary to replace each charecter such as this one: 我在字典中有一些代码来替换每个字符,例如:

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

( 'a' should be replaced by 'c' , 'd' by 'a' ...) 'a'应替换为'c''d'替换为'a' ......)

How can I convert the first string using the required characters from the dictionary to get the new string? 如何使用字典中的必需字符转换第一个字符串以获取新字符串? Here for example I should get "red car" as the new string. 例如,我应该将"red car"作为新字符串。

Try this: 尝试这个:

>>> 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'

Explanation: 说明:

>>> 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.

The maketrans line turns the dictionary into two separate strings suitable for input into maketrans : 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']
>>> 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'
"".join(code.get(k, k) for k in str)

would also work in your case. 也适用于你的情况。

code.get(k, k) returns code[k] if k is a valid key in code ; 如果kcode的有效密钥,则code.get(k, k)返回code[k] ; if it isn't, it returns k itself. 如果不是,则返回k本身。

though it would be tedious but a quick fix is str.replace("old", "new"). 虽然它会很乏味但快速修复是str.replace(“旧”,“新”)。 Here is the documentation for your help too http://www.tutorialspoint.com/python/string_replace.htm 以下是您的帮助文档http://www.tutorialspoint.com/python/string_replace.htm

Assuming you are using Python 2.x: 假设您使用的是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'
>>>print ''.join([code.get(s,s) for s in str])
'red car'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM