当前位置:首页 » 编程语言 » 字符串替换函数python

字符串替换函数python

发布时间: 2023-07-19 11:36:33

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()进行替换。

  • 可行的方法:

    1. 链式replace()

    ?

    1
  • string.replace().replace()
  • 1.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()#关闭文件
热点内容
ea服务器怎么连接 发布:2025-02-08 05:16:45 浏览:461
更加密更改 发布:2025-02-08 05:15:20 浏览:782
仓储资源配置都需要开展哪些任务 发布:2025-02-08 05:13:51 浏览:675
探针数据库 发布:2025-02-08 05:13:35 浏览:79
cfft算法 发布:2025-02-08 04:53:59 浏览:960
极客学院php 发布:2025-02-08 04:52:32 浏览:779
书本编译是什么意思 发布:2025-02-08 04:45:56 浏览:953
淘宝密码账号在哪里看 发布:2025-02-08 04:29:39 浏览:536
描绘四季的美文写一份朗读脚本 发布:2025-02-08 04:29:21 浏览:139
金蝶软件服务器是电脑吗 发布:2025-02-08 04:27:06 浏览:974