Home  >  Article  >  Backend Development  >  Detailed explanation of the usage skills of Python splitlines

Detailed explanation of the usage skills of Python splitlines

巴扎黑
巴扎黑Original
2017-05-21 18:50:471994browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn