翻译方法



maketrans()

maketrans() 方法返回一个映射表。它将 astr 中的每个字符映射到 bstr 中相同索引处的字符。此方法返回的映射表可由 translate() 方法用于替换字符。

语法

var.maketrans(astr, bstr, cstr)

参数

  • astr - 可以是字典或字符串。如果只提供一个参数,则此参数必须是字典。如果给出两个或多个参数,则此参数必须是指定要替换的字符的字符串。

  • bstr - 这是包含相应映射字符的字符串。

  • cstr - 可选。字符串参数指定要从字符串中删除的字符。

返回值

此方法返回一个要用于 translate() 函数的转换表。

示例

var = 'Explicit is better than implicit.'
table = var.maketrans({'i':'I'})
print ("original string:", var)
print ("translation table:", table)

var1 = var.translate(table)
print ("Translated string", var1)

var = "Explicit is better than implicit."
table = var.maketrans("than", "then")
print ("original string:", var)
print ("translation table:", table)
var2 = var.translate(table)
print ("Translated string", var2)

var = 'Explicit is better than implicit.'
table = var.maketrans("is","as", "s")
print ("original string:", var)
print ("translation table:", table)
var3=var.translate(table)
print ("Translated string", var3)

运行此程序时,将产生以下输出 -

original string: Explicit is better than implicit.
translation table: {105: 'I'}
Translated string ExplIcIt Is better than ImplIcIt.
original string: Explicit is better than implicit.
translation table: {116: 116, 104: 104, 97: 101, 110: 110}
Translated string Explicit is better then implicit.
original string: Explicit is better than implicit.
translation table: {105: 97, 115: None}
Translated string Explacat a better than amplacat.

translate()

translate() 方法返回一个字符串,其中每个字符都被 maketrans() 方法创建的转换表中的相应字符替换。

语法

var.translate(table)

参数

  • table - 由 maketrans() 方法创建的转换表。

返回值

此方法返回字符串的转换副本。

示例

var = 'Explicit is better than implicit.'
table = var.maketrans({'i':'I'})
print ("original string:", var)
print ("translation table:", table)

var1 = var.translate(table)
print ("Translated string", var1)

var = "Explicit is better than implicit."
table = var.maketrans("than", "then")
print ("original string:", var)
print ("translation table:", table)
var2 = var.translate(table)
print ("Translated string", var2)

var = 'Explicit is better than implicit.'
table = var.maketrans("is","as", "s")
print ("original string:", var)
print ("translation table:", table)
var3=var.translate(table)
print ("Translated string", var3)

运行此程序时,将产生以下输出 -

original string: Explicit is better than implicit.
translation table: {105: 'I'}
Translated string ExplIcIt Is better than ImplIcIt.
original string: Explicit is better than implicit.
translation table: {116: 116, 104: 104, 97: 101, 110: 110}
Translated string Explicit is better then implicit.
original string: Explicit is better than implicit.
translation table: {105: 97, 115: None}
Translated string Explacat a better than amplacat.
python_string_methods.htm
广告