Python 如何将多行字符串分割成多行
字符串是由多个字符组成的,可以用来表示一个单词或者整个短语。在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']