[英]String translate using dict
我想使用由dict
創建的字典,用其他字符替換字符向量中的字母,如下所示
import string
trans1 = str.maketrans("abc","cda")
trans = dict(zip("abc","cda"))
out1 = "abcabc".translate(trans1)
out = "abcabc".translate(trans)
print(out1)
print(out)
所需的輸出是"cdacda"
我得到的是
cdacda
abcabc
現在out1
是此所需的輸出,但out
不是。 我不知道為什么會這樣。 如何使用在translate
功能中通過字典創建的dict
? 那么,如果我想與trans
一起使用translate
,該怎么辦?
我認為translate
方法不會接受字典對象。 此外,您應該查看所創建的內容:
>>> dict(zip("abc","cda"))
{'c': 'a', 'a': 'c', 'b': 'd'}
我認為那不是您想要的。 zip
將第一個和第二個參數中對應索引的元素配對。
您可以編寫解決方法:
def translate_from_dict(original_text,dictionary_of_translations):
out = original_text
for target in dictionary_of_translations:
trans = str.maketrans(target,dictionary_of_translations[target])
out = out.translate(trans)
return out
trans = {"abc":"cda"}
out = translate_from_dict("abcabc",trans)
print(out)
使用dict
函數創建字典。 閱讀函數定義 。
>>> dict([("abc","cda")])
{"abc":"cda"}
str.translate
完全支持str.translate
(實際上,它支持任何支持索引的內容,即__getitem__
)–只是鍵必須是字符的序數表示,而不是字符本身。
相比:
>>> "abc".translate({"a": "d"})
'abc'
>>> "abc".translate({ord("a"): "d"})
'dbc'
string.translate
不支持使用字典作為參數:
translate(s, table, deletions='')
translate(s,table [,deletions]) -> string
Return a copy of the string s, where all characters occurring
in the optional argument deletions are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256. The
deletions argument is not allowed for Unicode strings.
因此,您必須編寫自己的函數。
另外,修改您的代碼,因為它不會在我知道的任何python版本中運行。 它至少有2個例外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.