如何将多行字符串拆分成多行?


字符串是由一系列字符组成的集合,可以用来表示单个单词或整个短语。字符串在 Python 中非常有用,因为它们不需要显式声明,并且可以用或不用说明符来定义。Python 包含多种内置方法和函数来处理和访问字符串。字符串是 String 类的对象,因为它包含多个方法,因为 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”。与 `splitlines()` 函数不同,`split()` 方法可以在任何字符处分割。我们只需要发送字符串应该在哪个字符处分割。

示例 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

在下面的示例中,我们使用相同的 `split()` 方法在新行处分割,但我们采用不同的方式获取输入。

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

更新于:2022-12-07

6K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.