字元串替換函數python
1. python 查找字元串並將其替換
f1=open('J:/wenjian/1/1.txt','r')
for line in f1
你這里是不是少了點什麼,f1隻是文件句柄,需要執行讀操作才能遍歷,
調用readlines()
確實有更好的代碼,那就是使用re.sub,它同時包含了查找和替換兩步的操作,
而不是像你寫的那樣的字元串比較性能那麼低
2. python 字元串替換問題
old='stsf'
pos=old.find('s')
if(pos!=-1):
new=old[:pos+1]+old[pos+1:].replace('s','A',1)
printnew
else:
print"Substring's'notfound!"
用字元串切片。
下面是更通用些的代碼(封裝成函數)。
defreplaceN(string,old,new,n):
'''Returnaofthestringwiththe'n'occurrenceofsubstring'old'replacedby'new'.
Ifsubstring'old'isnotfound,originalstringisreturned.
'''
if(n==1):returnstring.replace(old,new,1)
pos=-1;search=0
while(search<n-1):
search+=1
pos=string.find(old,pos+1)
if(pos==-1):returnstring
returnstring[:pos+1]+string[pos+1:].replace(old,new,1)
printreplaceN('stsftst','s','A',2)
3. python 字元串替換求解
使用正則,
#!/usr/bin/python
#-*-coding:UTF-8-*-
importre
phone="2004-959-559#這是一個國外電話號碼"
#刪除字元串中的Python注釋
num=re.sub(r'#.*$',"",phone)
print"電話號碼是:",num
#刪除非數字(-)的字元串
num=re.sub(r'D',"",phone)
print"電話號碼是:",num
以上實例執行結果如下:
電話號碼是: 2004-959-559
電話號碼是 : 2004959559
4. python讀取文本文件,如何將每行最後一個特定字元替換
方法:
解釋,s.count('/')計算原來有多少個特定字元串,然後第一步全部替換,第二步將count-1個還原
5. python如何使用re模塊的sub函數實現把一串字母或者數字組合的字元串,全部替換成*
改成
print re.sub("\w","*",_string3)
另外r作用是取消特殊意思
比如r"\a"則匹配\a的
6. python中如何對多個字元快速替換
python中快速進行多個字元替換的方法小結
先給出結論:
要替換的字元數量不多時,可以直接鏈式replace()方法進行替換,效率非常高;
如果要替換的字元數量較多,則推薦在 for 循環中調用replace()進行替換。
- string.replace().replace()
可行的方法:
1. 鏈式replace()
?
11.x 在for循環中調用replace()「在要替換的字元較多時」
2. 使用string.maketrans
3. 先 re.compile 然後 re.sub
7. python如何使用re模塊的sub函數實現把一串字母或者數字組合的字元串,全部替換成*
round(float(x), 6) 你要保留結尾的0的話,不能存成float數據,float會自動去掉末尾的0
你需要保存你的結果為string或者decimal.decimal
string的話:
"%.6f" % float(x)
decimal的話:
import decimal
decimal.decimal("%.6f" % float(x))
8. python將指定文本中的字元串替換後,生成新的文本文件。
Python替換某個文本中的字元串,然後生成新的文本文檔,代碼如下:
importos
os.chdir('D:\')#跳到D盤
ifnotos.path.exists('test1.txt'):#看一下這個文件是否存在
exit(-1)#不存在就退出
lines=open('test1.txt').readlines()#打開文件,讀入每一行
fp=open(''test2.txt','w')#打開你要寫得文件test2.txt
forsinlines:
#replace是替換,write是寫入
fp.write(s.replace('love','hate').replace('yes','no'))
fp.close()#關閉文件