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


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

replace()

python 中的 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中的單個字符,也可以替換連續的字符,但無法生成字符替換映射表

敲黑板!

pandas 里面也有一個replace()函數,其用法更加多樣化。比如,可以加入一個字典,用於替換對不同的值進行替換。

s = pd.Series([0, 1, 2, 3, 4])
s.replace({0:'a',1:'b'})
Out[2]: 
0    a
1    b
2    2
3    3
4    4
dtype: object

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用法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM