欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python將文本中的空格替換為換行的方法

 更新時間:2018年03月19日 21:04:46   作者:為援不可圖  
這篇文章主要介紹了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函數(shù)

Python3 replace()方法

描述
replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數(shù)max,則替換不超過 max 次。

語法
replace()方法語法:

str.replace(old, new[, max])

參數(shù)
old -- 將被替換的子字符串。
new -- 新字符串,用于替換old子字符串。
max -- 可選字符串, 替換不超過 max 次
返回值
返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個參數(shù)max,則替換不超過 max 次。

實(shí)例
以下實(shí)例展示了replace()函數(shù)的使用方法:

#!/usr/bin/python3
 
str = "歡迎訪問腳本之家www.dbjr.com.cn"
print ("腳本之家舊地址:", str)
print ("腳本之家新地址:", str.replace("jb51.net", "jbzj.com"))
 
str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))
以上實(shí)例輸出結(jié)果如下:

腳本之家舊地址: 歡迎訪問腳本之家www.dbjr.com.cn
腳本之家新地址: 歡迎訪問腳本之家www.jbzj.com
thwas was string example....wow!!!

相關(guān)文章

最新評論