1. 程式人生 > >Python3字符串替換replace(),translate(),re.sub()

Python3字符串替換replace(),translate(),re.sub()

標準庫 src bye 總結 abc ctu blog clas XA

Python3的字符串替換,這裏總結了三個函數,replace()translate()re.sub()

replace()

replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數max,則替換不超過 max 次

str.replace(old, new[, max])

a = ‘Hello,world. ByeBye!‘
print(a.replace(‘l‘,‘Q‘))
print(a.replace(‘abcdefghi‘,‘0123456789‘))
print(a.replace(‘world‘,‘apple‘))
HeQQo,worQd. ByeBye!
Hello,world. ByeBye!
Hello,apple. ByeBye!

可見,replace()函數可以替換string中的單個字符,也可以替換連續的字符,但無法生成字符替換映射表

translate()

translate()函數也是python自帶。與replace() 函數不同的是,這裏使用str.maketrans函數來創建一個表,它可以使用各種參數,但是需要三個Arguments。

str.maketrans(‘‘,‘‘,del)

第一個參數為被替換的字符,第二個參數為替換的字符,第三個參數為要刪除的字符

import string
a = ‘Hello,world. ByeBye!‘
remove = string.punctuation
table =
str.maketrans(‘abcdefgh‘,‘01234567‘,remove) print(a.translate(table))
H4lloworl3 By4By4

string.punctuation返回所有的標點符號,更多字符串常量如下圖:
技術分享圖片

str.maketrans()的前兩個參數相當於一個映射表,如上述結果,所有的‘e‘被替換成了‘4‘

第三個參數為要刪除的字符,上述例子刪除了所有的標點符號,如果要刪除的字符還要加上空格的話,則可以這樣:

table = str.maketrans(‘abcdefgh‘,‘01234567‘,remove+‘ ‘)
print(a.translate(table))
H4lloworl3By4By4

re.sub()

這個是re庫裏的函數,其原型為re.sub(pattern, repl, string, count)

第一個參數為正則表達式需要被替換的參數,第二個參數是替換後的字符串,第三個參數為輸入的字符串,第四個參數指替換個數。默認為0,表示每個匹配項都替換。

import re
a = ‘Hello,world. ByeBye!‘
print(re.sub(r‘[A-Z]‘, ‘8‘, a))
8ello,world. 8ye8ye!

上述例子是把所有的大寫字母替換成8,下述表示只替換前2個這樣的大寫字母。

print(re.sub(r‘[A-Z]‘, ‘8‘, a, 2))
8ello,world. 8yeBye!
  • Reference:
  1. Python3 replace()方法
  2. NLP-python3 translate()報錯問題-TypeError: translate() takes exactly one argument (2 given
  3. Python 標準庫筆記:string模塊
  4. 關於python 的re.sub用法

Python3字符串替換replace(),translate(),re.sub()