如何在 Python 中创建多行长字符串?
在这篇文章中,我们将重点介绍如何在 Python 中创建多行长字符串。
第一种方法是使用三引号,我们应该添加一个三引号,然后我们可以在引号内添加分开的行,这样就创建了多行字符串。
在 Python 中使用三引号,可以将字符串跨越多行。它还可以应用于冗长的代码注释。三引号还可以包含特殊字符,如 TAB、逐字或换行符。顾名思义,语法由三个连续的单引号或双引号组成。
示例
在下面给出的程序中,我们正在获取一个多行字符串作为输入,并打印它−
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP