本文目錄一覽:
python 字元串替換求解
使用正則,
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
phone = “2004-959-559 # 這是一個國外電話號碼”
# 刪除字元串中的 Python注釋
num = re.sub(r’#.*$’, “”, phone)
print “電話號碼是: “, num
# 刪除非數字(-)的字元串
num = re.sub(r’\D’, “”, phone)
print “電話號碼是 : “, num
以上實例執行結果如下:
電話號碼是: 2004-959-559
電話號碼是 : 2004959559
Python正則表達式如何進行字元串替換
Python正則表達式在使用中會經常應用到字元串替換的代碼。有很多人都不知道如何解決這個問題源碼天空,下面的代碼就告訴你其實這個問題無比的簡單,希望你有所收穫。1.替換所有匹配的子串用newstring替換subject中所有與正則表達式regex匹配的子串result, number = re.subn(regex, newstring, subject) 2.替換所有匹配的子串(使 用正則表達式對象)rereobj = re.compile(regex) result, number = reobj.subn(newstring, subject)字元串拆分 Python字元串拆分reresult = re.split(regex, subject) 字元串拆分(使用正則表示式對象)rereobj = re.compile(regex) result = reobj.split(subject)匹配 下面列出Python正則表達式的幾種匹配用法:1.測試正則表達式是否 匹配字元串的全部或部分regex=ur”…” #正則表達式if re.search(regex, subject): do_something() else:do_anotherthing()2.測試正則表達式是否匹配整個字元串regex=ur”…\Z” #正則表達式末尾以\Z結束if re.match(regex, subject): do_something() else: do_anotherthing() 3. 創建一個匹配對象,然後通過該對象獲得匹配細節regex=ur”…” #正則表達式match = re.search(regex, subject) if match: # match start: match.start() # match end (exclusive): match.end() # matched text: match.group() do_something() else: do_anotherthing() 以上就是對Python正則表達式在字元串替換中的具體介紹。
python 字元串替換
str=’aaaaaaaaaa’
ls = list(str)
ls[2] = ‘0’
ls[3] = ‘0’
ls[4] = ‘0’
ls[5] = ‘0’
ls[6] = ‘0’
new_str = ”.join(ls) # ‘aa00000aaa’
python 中怎麼替換字元串
Python替換某個文本中的字元串,然後生成新的文本文檔,代碼如下:import osos.chdir(‘D:\\’) # 跳到D盤if not os.path.exists(‘test1.txt’): # 看一下這個文件是否存在exit(-1) #不存在就退出lines = open(‘test1.txt’).readlines() #打開文件,讀入每一行fp = open(”test2.txt’,’w’) #打開你要寫得文件test2.txtfor s in lines:# replace是替換,write是寫入fp.write( s.replace(‘love’,’hate’).replace(‘yes’,’no’)) fp.close() # 關閉文件
如何用Python來進行查詢和替換一個文本字元串
1、說明
可以使用find或者index來查詢字元串,可以使用replace函數來替換字元串。
2、示例
1)查詢
‘abcdefg’.find(‘cde’)
結果為2
‘abcdefg’.find(‘acde’)
結果為-1
‘abcdefg’.index(‘cde’)
結果為2
2)替換
‘abcdefg’.replace(‘abc’,’cde’)
結果為’cdedefg’
3、函數說明
1)find(…)
S.find(sub[, start[, end]]) – int
返回S中找到substring sub的最低索引,使得sub包含在S [start:end]中。 可選的 參數start和end解釋為切片表示法。
失敗時返回-1。
2)index(…)
S.index(sub[, start[, end]]) – int
與find函數類似,但是當未找到子字元串時引發ValueError。
3)replace(…)
S.replace(old, new[, count]) – str
返回S的所有出現的子串的副本舊換新。 如果可選參數計數為給定,只有第一個計數出現被替換。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/279719.html