2011-12-03 100 views
2

我試圖找到做以下的最佳方法:如何替換Python中的字符串中的字符?

我有一個字符串可以說:

str = "pkm adp" 

和我有一本字典一定的代碼來替換性格特徵的每一個像這樣的之一:

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

'a''c'更換,'d'通過'a' ...)

如何使用字典中的所需字符來轉換第一個字符串以獲取新字符串?在這裏例如我應該得到"red car"作爲新的字符串。

回答

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

也適用於您的情況。

code.get(k, k)返回code[k]如果kcode中的有效鍵;如果不是,則返回k本身。

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' 
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'] 
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' 
0
>>>print ''.join([code.get(s,s) for s in str]) 
'red car'