python将文本中的空格替换为换行的方法
测试文本 jb51.txt
welcome to jb51.net
I love you very much
python代码
# -*- coding: utf-8 -*- ''' 遇到文中的空格就换行 ''' def delblankline(infile, outfile): infopen = open(infile, 'r',encoding="utf-8") outfopen = open(outfile, 'w',encoding="utf-8") db = infopen.read() outfopen.write(db.replace(' ','\n')) infopen.close() outfopen.close() delblankline("jb51.txt", "o3.txt")
效果图
主要就是用到了replace函数
Python3 replace()方法
描述
replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法
replace()方法语法:
str.replace(old, new[, max])
参数
old -- 将被替换的子字符串。
new -- 新字符串,用于替换old子字符串。
max -- 可选字符串, 替换不超过 max 次
返回值
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。
实例
以下实例展示了replace()函数的使用方法:
#!/usr/bin/python3 str = "欢迎访问脚本之家www.jb51.net" print ("脚本之家旧地址:", str) print ("脚本之家新地址:", str.replace("jb51.net", "jbzj.com")) str = "this is string example....wow!!!" print (str.replace("is", "was", 3))
脚本之家旧地址: 欢迎访问脚本之家www.jb51.net
脚本之家新地址: 欢迎访问脚本之家www.jbzj.com
thwas was string example....wow!!!
相关文章
pytorch中F.avg_pool1d()和F.avg_pool2d()的使用操作
这篇文章主要介绍了pytorch中F.avg_pool1d()和F.avg_pool2d()的使用操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-05-05Python判断字符串是否包含特定子字符串的多种方法(7种方法)
我们经常会遇这样一个需求判断字符串中是否包含某个关键词,也就是特定的子字符串,接下来通过本文给大家分享Python判断字符串是否包含特定子字符串的多种方法(7种方法),需要的朋友可以参考下2023-03-03
最新评论