Python 如何按照换行符拆分

Python 如何按照换行符拆分

在本文中,我们将讨论如何在Python中按照换行符拆分。

一般来说,拆分意味着将一组对象分割成小组。

在Python中,第一种按照 换行符 拆分的方法是使用内置方法 splitlines() 。它接受一个多行字符串作为输入,并返回一个以换行符分割的字符串。它不接受任何参数。

splitlines() 方法是内置的字符串方法,仅用于按照换行符进行拆分。

示例1

在下面的程序中,我们输入一个多行字符串,并使用 splitlines() 方法在换行符处拆分字符串。

str1 = "Welcome\nto\nTutorialspoint"

print("The given string is")
print(str1)

print("The resultant string split at newline is")
print(str1.splitlines())

输出

上述示例的输出如下所示:

The given string is
Welcome
to
Tutorialspoint
The resultant string split at newline is
['Welcome', 'to', 'Tutorialspoint']

示例2

在下面给出的示例中,我们使用相同的splitlines()方法在换行符处进行分割,但我们以不同的方式输入数据 −

str1 = """Welcome
To
Tutorialspoint"""

print("The given string is")
print(str1)

print("The resultant string split at newline is")
print(str1.splitlines())

输出

上面示例的输出如下所示:

The given string is
Welcome
to
Tutorialspoint
The resultant string split at newline is
['Welcome', 'to', 'Tutorialspoint']

使用split()方法

第二种方法是使用内置的方法 split() 。我们需要提供一个参数,即我们希望给定的字符串在哪个字符处分割。所以,如果我们想要在换行处分割,我们应该将’\n’作为参数。split()方法可以用于在任何字符处分割,不同于 splitlines() 方法。我们只需要提供我们希望字符串分割的字符。

示例1

在下面给出的示例中,我们输入一个字符串,并使用split()方法在换行处分割字符串。

str1 = "Welcome\nto\nTutorialspoint"

print("The given string is")
print(str1)

print("The resultant string split at newline is")
print(str1.split('\n'))

输出

上述示例的输出如下:

The given string is
Welcome
to
Tutorialspoint
The resultant string split at newline is
['Welcome', 'to', 'Tutorialspoint']

示例2

在下面给出的示例中,我们使用与上面相同的程序,但我们选择了一个不同的子字符串并进行检查。−

str1 = """Welcome
To
Tutorialspoint"""

print("The given string is")
print(str1)

print("The resultant string split at newline is")
print(str1.split('\n'))

输出

上述示例的输出如下:

The given string is
Welcome
to
Tutorialspoint
The resultant string split at newline is
['Welcome', 'to', 'Tutorialspoint']

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程