Python 字符串转换方法
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.