【python cookbook】改变多行文本字符串的缩进
2012-07-23 11:17
549 查看
任务:有一个多行文本的字符串需要创建该字符串的一个拷贝,并在每行行首添加或删除一些空格,以保证每行缩进都是指定数目的空格数
利用字符串对象提供的strip()s.splitlines()可以很快的实现
如果要调整每行的空格数并保证相对缩进不变
s.splitlines()用法
str.splitlines([keepends])
Returnalistofthelinesinthestring,breakingatlineboundaries.Linebreaksarenotincludedintheresultinglistunlesskeependsisgivenandtrue.Thismethodusestheuniversalnewlinesapproachtosplittinglines.Unlikesplit(),ifthestringendswithlineboundarycharactersthereturnedlistdoesnothaveanemptylastelement.
Forexample,'abc\n\ndefg\rkl\r\n'.splitlines()returns['abc','','defg','kl'],whilethesamecallwithsplitlines(True)returns['abc\n','\n,'defg\r','kl\r\n'].
lstrip用法()string.lstrip(s[,chars])
Returnacopyofthestringwithleadingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromthebeginningofthestringthismethodiscalledon.
去除首部指定字符若不指定默认去掉空格
rstrip用法()string.rstrip(s[,chars])
Returnacopyofthestringwithtrailingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromtheendofthestringthismethodiscalledon.
去除尾部指定字符若不指定默认去掉空格
strip用法()string.strip(s[,chars])
Returnacopyofthestringwithleadingandtrailingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromthebothendsofthestringthismethodiscalledon.
去除字符串两端指定字符若不指定默认去掉空格
str.split([sep[,maxsplit]])
Returnalistofthewordsinthestring,usingsepasthedelimiterstring.Ifmaxsplitisgiven,atmostmaxsplitsplitsaredone(thus,thelistwillhaveatmostmaxsplit+1elements).Ifmaxsplitisnotspecifiedor-1,thenthereisnolimitonthenumberofsplits(allpossiblesplitsaremade).
Ifsepisgiven,consecutivedelimitersarenotgroupedtogetherandaredeemedtodelimitemptystrings(forexample,'1,,2'.split(',')returns['1','','2']).Thesepargumentmayconsistofmultiplecharacters(forexample,'1<>2<>3'.split('<>')returns['1','2','3']).Splittinganemptystringwithaspecifiedseparatorreturns[''].
IfsepisnotspecifiedorisNone,adifferentsplittingalgorithmisapplied:runsofconsecutivewhitespaceareregardedasasingleseparator,andtheresultwillcontainnoemptystringsatthestartorendifthestringhasleadingortrailingwhitespace.Consequently,splittinganemptystringorastringconsistingofjustwhitespacewithaNoneseparatorreturns[].
Forexample,'123'.split()returns['1','2','3'],and'123'.split(None,1)returns['1','23'].
利用字符串对象提供的strip()s.splitlines()可以很快的实现
#!/usr/bin/python #-*-coding:utf-8-*- #改变多行文本的缩进 defreindent(s,numSpaces): leading_space=numSpaces*'' lines=[leading_space+line.strip()forlineins.splitlines()] return'\n'.join(lines)
如果要调整每行的空格数并保证相对缩进不变
defaddSpaces(s,numAdd): #计算原有空格数和需要添加的空格数的总和 white=''*numAdd returnwhite+white.join(s.splitlines) defnumSpaces(s): #返回每行空格数的列表 return[len(line)-len(line.lstrip())forlineins.splitlines()] defdelSpaces(s,numDel): ifnumDel>min(numSpaces(s)): raiseValueError,"removingmorespacesthanthereare!" return'\n'.join([line[numDel:]forlineins.splitlines()])
s.splitlines()用法
str.splitlines([keepends])
Returnalistofthelinesinthestring,breakingatlineboundaries.Linebreaksarenotincludedintheresultinglistunlesskeependsisgivenandtrue.Thismethodusestheuniversalnewlinesapproachtosplittinglines.Unlike
Forexample,'abc\n\ndefg\rkl\r\n'.splitlines()returns['abc','','defg','kl'],whilethesamecallwithsplitlines(True)returns['abc\n','\n,'defg\r','kl\r\n'].
>>>a="""first
second
third
"""
>>>a.splitlines()
['first','second','third','']
lstrip用法()string.lstrip(s[,chars])
Returnacopyofthestringwithleadingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromthebeginningofthestringthismethodiscalledon.
去除首部指定字符若不指定默认去掉空格
rstrip用法()string.rstrip(s[,chars])
Returnacopyofthestringwithtrailingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromtheendofthestringthismethodiscalledon.
去除尾部指定字符若不指定默认去掉空格
strip用法()string.strip(s[,chars])
Returnacopyofthestringwithleadingandtrailingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromthebothendsofthestringthismethodiscalledon.
去除字符串两端指定字符若不指定默认去掉空格
str.split([sep[,maxsplit]])
Returnalistofthewordsinthestring,usingsepasthedelimiterstring.Ifmaxsplitisgiven,atmostmaxsplitsplitsaredone(thus,thelistwillhaveatmostmaxsplit+1elements).Ifmaxsplitisnotspecifiedor-1,thenthereisnolimitonthenumberofsplits(allpossiblesplitsaremade).
Ifsepisgiven,consecutivedelimitersarenotgroupedtogetherandaredeemedtodelimitemptystrings(forexample,'1,,2'.split(',')returns['1','','2']).Thesepargumentmayconsistofmultiplecharacters(forexample,'1<>2<>3'.split('<>')returns['1','2','3']).Splittinganemptystringwithaspecifiedseparatorreturns[''].
IfsepisnotspecifiedorisNone,adifferentsplittingalgorithmisapplied:runsofconsecutivewhitespaceareregardedasasingleseparator,andtheresultwillcontainnoemptystringsatthestartorendifthestringhasleadingortrailingwhitespace.Consequently,splittinganemptystringorastringconsistingofjustwhitespacewithaNoneseparatorreturns[].
Forexample,'123'.split()returns['1','2','3'],and'123'.split(None,1)returns['1','23'].
相关文章推荐
- 001_014 Python 改变多行文本字符串的缩进
- 基于《PythonCookbook》的学习(2)——在字符串的卡头或结尾做文本匹配
- 《Python CookBook2》 第一章 文本 - 改变多行文本字符串的缩进 && 扩展和压缩制表符(此节内容待定)
- python cookbook 字符串和文本
- python cookbook第三版学习笔记四:文本以及字符串令牌解析
- 改变多行文本字符串的缩进
- Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作
- 【python cookbook】python检查一个字符串是文本还是二进制
- Python cookbook(字符串与文本)针对任意多的分隔符拆分字符串操作示例
- python cookbook:第二章 字符串和文本
- python字符串的操作——python cookbook
- 基于《PythonCookbook》的学习(1)——针对任意多的分隔符拆分字符串
- Python Cookbook 第二版 汉化版 [Recipe 1.7] 以单词或字符为单位对字符串进行反序排列
- 【python cookbook】简化字符串的translate 方法的使用
- python cookbook 学习笔记 -- 1.7 将字符串逐字符或逐词反转
- python cookbook 学习笔记 -- 1.8 检查字符串中是否包含某字符集合中的字符
- 【python cookbook】 将字符串逐字符或逐词反转
- Python Cookbook 第二版 汉化版 [Recipe 1.8] 检测字符串是否包含特定的字符集合
- python cookbook 学习笔记 -- 1.5 去除字符串两端空格
- 【python cookbook】 检查字符串中是否包含某自符集合中的字符