Home >Backend Development >Python Tutorial >Detailed explanation of the usage skills of Python splitlines
Splitlines in Python are used to split lines. When the parameter passed in is True, it means that the newline character \n is retained. It will be clear from the following example
The code is as follows:
mulLine = """Hello!!! Wellcome to Python's world! There are a lot of interesting things! Enjoy yourself. Thank you!""" print ''.join(mulLine.splitlines()) print '------------' print ''.join(mulLine.splitlines(True))
Output result:
Hello!!! Wellcome to Python's world! There are a lot of interesting things! Enjoy yourself. Thank you! ------------ Hello!!! Wellcome to Python's world! There are a lot of interesting things! Enjoy yourself. Thank you!
Using this function, you can write something very convenient Paragraph processing functions, such as processing indentation and other methods. Such as the example in the Cookbook:
The code is as follows:
def addSpaces(s, numAdd): white = " "*numAdd return white + white.join(s.splitlines(True)) def numSpaces(s): return [len(line)-len(line.lstrip( )) for line in s.splitlines( )] def delSpaces(s, numDel): if numDel > min(numSpaces(s)): raise ValueError, "removing more spaces than there are!" return '\n'.join([ line[numDel:] for line in s.splitlines( ) ]) def unIndentBlock(s): return delSpaces(s, min(numSpaces(s)))
The above is the detailed content of Detailed explanation of the usage skills of Python splitlines. For more information, please follow other related articles on the PHP Chinese website!