Python 如何创建多行字符串
在本文中,我们将专注于如何在Python中创建一个长的多行字符串。
第一种方法是使用三重引号,我们应该在引号内添加三重引号,然后我们可以在引号内添加单独的行,从而创建多行字符串。
在Python中使用三重引号,可以将字符串跨多行。它也可以应用于冗长的代码注释。三重引号还可以包含特殊字符,如制表符、原样输出或换行符。顾名思义,语法由三个连续放置的单引号或双引号组成。
示例
在下面给出的程序中,我们将输入一个多行字符串,并将其打印出来。
str1 ="""Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you
"""
print("The multi-line string is")
print(str1)
输出
上面示例的输出如下所示−
The multi-line string is
Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you
使用括号
第二种方法是使用括号和多个双引号。我们必须将整个字符串放在括号内,在每行完成后加入换行符(\n)并添加新行。
示例
在下面的示例中,我们使用括号获取多行字符串并打印出来 –
str1 =("Welcome to Tutorialspoint\n"
"How are you doing?\n"
"Hope everything is fine\n"
"Thank you")
print("The multi-line string is")
print(str1)
输出
上述示例的输出如下所示 –
The multi-line string is
Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you
使用\和换行字符
第三种方法是使用 **** 和换行字符。这与上述方法类似,但我们不包括每个换行字符后的括号,而是在每个新行字符后包括\。
示例
在下面的示例中,我们使用括号获取一个多行字符串并打印它。−
str1 ="Welcome to Tutorialspoint\n"\
"How are you doing?\n"\
"Hope everything is fine\n"\
"Thank you"
print("The multi-line string is")
print(str1)
输出
上述示例的输出如下:
The multi-line string is
Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you