您的位置:首页 > 编程语言 > Python开发

【python cookbook】改变多行文本字符串的缩进

2012-07-23 11:17 549 查看
任务:有一个多行文本的字符串需要创建该字符串的一个拷贝,并在每行行首添加或删除一些空格,以保证每行缩进都是指定数目的空格数

利用字符串对象提供的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.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'].



>>>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'].


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐