2

我以为我知道不同类型的 Python 引用意味着什么,但对这个例子有点困惑:

my_string = 'the cat sat on the mat' 
my_string = "the cat sat on the mat" 
my_string = """the cat sat on the mat""" 
my_string = '''the cat sat on the mat'''

前两个似乎是使用单引号或双引号声明字符串的两种不同方式。最后两个似乎是使表达式不完整的注释(并且会在解释器中产生错误。对吗?

4

2 回答 2

5

最后两个不是注释,它们是多行字符串,如果你打印出最后两个字符串,你会看到你在控制台上得到输出。

my_string3 = """the cat sat on the mat"""

print my_string3
>>> the cat sat on the mat

如果"""..."""表示注释,那么您必须在初始化此类变量时收到错误消息,否则a = #dad会引发错误。

由于初始化的字符串"""是多行的,因此我们可以将一些字符串初始化为:

my_string3 = """the
cat sat on 
the mat""" 

print my_string3
>>> the
    cat sat on 
    the mat
于 2015-06-03T06:32:34.400 回答
1

例子:

text1 = "This is s single-line text with doubles"
text2 = 'This is s single-line text too but with singles'
text3 = "FallenAngel'S text should have doubles since there is an apostrophe in the string and signles would cause problems"

text4 = """This is a
        multi line string, and the output would be multi-line too"""
text5 = '''This is another multi-line.
        Both multi-lines generally used in writing Sql Query strings
        and this style makes them more readable'''
text6 = """Single line triple quotes are ok, but they do not look much useful"""
text7 = '''This is ok too, but as I said, it is not common and not pretty.'''

def somefunc():
    """And this is a doc-string. Python advice using triple double quotes in doc-strings even if they are single line"""
    pass
于 2015-06-03T06:53:11.757 回答