📜  Python中的三引号

📅  最后修改于: 2022-05-13 01:55:31.850000             🧑  作者: Mango

Python中的三引号

可以使用 python 的三引号将字符串跨越多行。它也可以用于代码中的长注释。特殊字符,如 TAB、逐字或 NEWLINE 也可以在三引号中使用。顾名思义,它的语法由三个连续的单引号或双引号组成。

注意:根据官方Python文档,三引号是文档字符串或多行文档字符串,不被视为注释。三引号内的任何内容都由解释器读取。当解释器遇到哈希符号时,它会忽略之后的所有内容。这就是评论的定义。

多行字符串的三引号

Python3
"""This is a really long comment that can make
the code look ugly and uncomfortable to read on
a small screen so it needs to be broken into
multi-line strings using double triple-quotes"""
 
print("hello Geeks")


Python3
'''This is a really long comment that can make
the code look ugly and uncomfortable to read on
a small screen so it needs to be broken into
multi-line strings using double triple-quotes'''
 
print("hello Geeks")


Python3
str1 = """I """
str2 = """am a """
str3 = """Geek"""
 
# check data type of str1, str2 & str3
print(type(str1))
print(type(str2))
print(type(str3))
 
print(str1 + str2 + str3)


Python3
my_str = """I
am
a
Geek !"""
 
# check data type of my_str
print(type(my_str))
 
print(my_str)


Python3
my_str = """I \
am \
a \
Geek !"""
 
# check data type of my_str
print(type(my_str))
 
print(my_str)


输出:
hello Geeks

同样,单三引号也可以用于相同的目的,如下所示:

Python3

'''This is a really long comment that can make
the code look ugly and uncomfortable to read on
a small screen so it needs to be broken into
multi-line strings using double triple-quotes'''
 
print("hello Geeks")
输出:
hello Geeks

注意:我们也可以在多行中使用#,但三引号看起来要好得多。

用于创建字符串的三引号

三引号的另一个用例是在Python中创建字符串。在三引号内添加所需的字符可以将这些字符转换为Python字符串。以下代码显示了使用三引号创建字符串:

示例 1:

Python3

str1 = """I """
str2 = """am a """
str3 = """Geek"""
 
# check data type of str1, str2 & str3
print(type(str1))
print(type(str2))
print(type(str3))
 
print(str1 + str2 + str3)
输出:



I am a Geek

示例 2:
使用三引号的多行字符串。默认情况下包括行尾。

Python3

my_str = """I
am
a
Geek !"""
 
# check data type of my_str
print(type(my_str))
 
print(my_str)
输出:

I
am
a
Geek !

示例 3:
如果我们希望忽略行尾,我们需要使用 ” 。

Python3

my_str = """I \
am \
a \
Geek !"""
 
# check data type of my_str
print(type(my_str))
 
print(my_str)
输出:

I am a Geek !