Python 3字符串 translate () 方法
Python 3中的字符串有一個非常有用的方法,即translate()
。愛掏網(wǎng) - it200.com這個方法可以替換或刪除字符串中指定的字符或字符集,文本處理中非常實用。愛掏網(wǎng) - it200.com
translate()
方法可以接受一個字符映射表,其中每個字符都對應(yīng)另一個字符或者為空。愛掏網(wǎng) - it200.com這個字符映射表可以使用Python內(nèi)置的maketrans()
方法來創(chuàng)建。愛掏網(wǎng) - it200.com下面是一個簡單的示例:
#創(chuàng)建一個字符映射表
transTable = str.maketrans("aeiou", "12345")
# 使用映射表替換字符串中的字符
string = "hello world"
translatedString = string.translate(transTable)
print(translatedString)
代碼執(zhí)行結(jié)果如下:
h2ll4 w4rld
上例中,我們使用了對元音字符a, e, i, o, u的映射,這些字符在字符串中被替換為數(shù)字1, 2, 3, 4, 5。愛掏網(wǎng) - it200.com這個字符映射表被用于translate()
方法中,把字符串中的所有元音字母都進行了替換。愛掏網(wǎng) - it200.com
translate()
函數(shù)可以接受一個可選的參數(shù),指定需要被刪除的字符集。愛掏網(wǎng) - it200.com下面的示例演示了如何刪除字符串中的所有數(shù)字:
# 創(chuàng)建一個字符映射表和字符集
transTable = str.maketrans("", "", "0123456789")
# 使用映射表及字符集刪除字符串中的數(shù)字
string = "a1b2c3d4e5f6g7"
translatedString = string.translate(transTable)
print(translatedString)
代碼執(zhí)行結(jié)果如下:
abcdefg
上例中,我們傳遞了一個空字符串作為第一個參數(shù),表示不進行任何替換。愛掏網(wǎng) - it200.com第三個參數(shù)表示需要從字符串中刪除的字符集,這里是所有數(shù)字字符。愛掏網(wǎng) - it200.com
在翻譯過程中改變字符串大小寫
除了替換和刪除字符,translate()
方法還可以方便地轉(zhuǎn)換字符串中的字符大小寫。愛掏網(wǎng) - it200.com下面是一個演示如何把所有的大寫字母換成小寫字母的示例代碼:
# 創(chuàng)建一個字符映射表
transTable = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
# 使用映射表替換字符串中的所有大寫字母為小寫字母
string = "Hello World"
translatedString = string.translate(transTable)
print(translatedString)
代碼執(zhí)行結(jié)果如下:
hello world
上例中,我們定義了一個字符映射表,用于把所有大寫字母映射為小寫字母。愛掏網(wǎng) - it200.com我們把這個字符映射表傳遞給了translate()
方法,并把Hello World
字符串中的大寫字母都轉(zhuǎn)換成了小寫字母。愛掏網(wǎng) - it200.com
translate()
方法與正則表達式的比較
translate()
方法與正則表達式有一些相似之處,都可以用于替換指定的字符或刪除字符。愛掏網(wǎng) - it200.com不過,translate()
方法更加方便快捷,通常優(yōu)于正則表達式。愛掏網(wǎng) - it200.com
下面是一個使用正則表達式替換字符串中所有數(shù)字的示例代碼:
import re
# 使用正則表達式查找并替換字符串中的數(shù)字
string = "a1b2c3d4e5f6g7"
regex = re.compile(r'\d')
replacedString = regex.sub("", string)
print(replacedString)
代碼執(zhí)行結(jié)果如下:
abcdefg
上例中,我們使用了sub()
方法替換字符串中所有數(shù)字。愛掏網(wǎng) - it200.com這個方法需要使用正則表達式來定義需要被替換的字符集。愛掏網(wǎng) - it200.com
與之相比,translate()
方法用起來更加簡單。愛掏網(wǎng) - it200.com因為translate()
方法可以直接通過映射表來替換字符,所以不需要使用正則表達式。愛掏網(wǎng) - it200.com在某些情況下,使用translate()
方法也可以獲得更好的性能。愛掏網(wǎng) - it200.com