python 小知識點 多字串替換

2021-10-08 07:39:35 字數 1492 閱讀 7089

乙個長字串或者乙個文字檔案做資料分析的時候經常遇到需要排除干擾項的需求,這時候就需要多字串替換的功能

使用str的 replace函式

字串常用的替換函式

比如說將標點替換成,使用replace連續替換多次即可

s = '''

there was a card party at the rooms of naroumoff, of the horse guards.

the long winter night passed away imperceptibly, and it was five o'clock in the morning before the company sat down

'''b = s.replace(",", "").replace(".", "").replace(";", "")

print(b)

使用re 的sub函式替換
import re

s = '''

there was a card party at the rooms of naroumoff, of the horse guards.

the long winter night passed away imperceptibly, and it was five o'clock in the morning before the company sat down

'''words = ["when", "there", "those", "the"]

def replace_re():

pattern = re.compile("|".join(words))

print(pattern)

r = re.sub(pattern, "", s) # 全部替換成空

print(r)

如果你需要指定字元替換成指定字元的話:

import re

s = '''

there was a card party at the rooms of naroumoff, of the horse guards.

the long winter night passed away imperceptibly, and it was five o'clock in the morning before the company sat down

'''words =

def replace_re():

rep = dict((re.escape(k), v) for k, v in words.items())

pattern = re.compile("|".join(rep.keys()))

r = pattern.sub(lambda m: rep[re.escape(m.group(0))], s)

print(r)

python 小知識點 字串處理

對於字串的處理無論是哪種語言都是相當重要的 python對於字串的處理提供了大量的內建函式 必須掌握兩種計算字串處理技巧 另乙個必備的字串處理技能是 能夠利用給定程式語言的標準庫進行基本的字串操作 字串表示方法 常用操作 s 12345678 print s 3 提取第四個字元 print s 3 ...

字串小知識點

1 字串操作 strcpy p,p1 複製字串 strncpy p,p1,n 複製指定長度字串 strcat p,p1 附加字串 strncat p,p1,n 附加指定長度字串 strlen p 取字串長度 strcmp p,p1 比較字串 strcasecmp忽略大小寫比較字串 strncmp p...

Python字串知識點總結

a abc b a 1 字串反轉 c a 1 3 字串擷取,下標從0開始,謹記左開右閉 print a,b,c out abc cba bcnum 3.1415926 print f 小數點後取3位,注意是四捨五入的 out 3.1416str1 this is string example wow...