功能中的不同引用类型

2024-04-18 17:19:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想弄清楚不同的报价类型是否在功能上有所不同。我见过有人说它偏爱""或{},但{}呢?我用一个简单的代码测试了它,看看它是否可以工作,它确实起作用了。我想知道""" triple quotes """是否对定义的函数参数有功能用途,或者它只是另一个可以互换使用的引号选项,比如""和{}?在

正如我看到的许多人关于""''的帖子,我没有看到过关于""" """或{}在函数中使用的帖子。在

我的问题是:三重引号作为一个参数有独特的用途,还是可以简单地与""和{}互换?我认为它可能有一个独特的函数是因为它是一个多行引号,我想知道它是否允许提交一个多行参数。我不确定这样的东西是否有用,但可能有用。在

下面是一个示例,它使用我知道的所有报价类型打印出您期望的结果。在

def myFun(var1="""different""",var2="quote",var3='types'):
    return var1, var2, var3

print (myFun('All','''for''','one!'))

结果:

^{pr2}$

编辑:

在对三重引号进行了更多的测试之后,我确实在函数中使用return和printing时发现了一些变化。在

def myFun(var1="""different""",var2="""quote""",var3='types'):
    return (var1, var2, var3)

print(myFun('This',
'''Can
Be
Multi''',
'line!'))

结果:

('This', 'Can\nBe\nMulti', 'line!')

或者:

def myFun(var1="""different""",var2="""quote""",var3='types'):
    print (var1, var2, var3)

myFun('This',
'''Can
Be
Multi''',
'line!')

结果:

This Can
Be
Multi line!

Tags: 函数returndeflinethiscan引号quote
2条回答

来自the docs

String literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). [...other rules applying identically to all string literal types omitted...]

In triple-quoted strings, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the string. (A “quote” is the character used to open the string, i.e. either ' or ".)

因此,三重引号字符串文本可以跨越多行,并且可以包含不使用转义序列的文本引号,但是在其他方面与用其他引号类型表示的字符串文本完全相同(包括那些使用转义序列如\n或{}来表示相同内容的字符串文本)。在

另请参阅Python3文档:Bytes and String Literals,它用稍微不同的措辞表达了一组完全相同的规则。在


language tutorial中还提供了一个更温和的介绍,它显式地引入了三引号,作为允许字符串跨越多行的一种方式:

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

produces the following output (note that the initial newline is not included):

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

不过,需要澄清的是:这些语法是不同的,但是它们创建的字符串文本彼此之间没有区别。也就是说,给定以下代码:

s1 = '''foo
'bar'
baz
'''
s2 = 'foo\n\'bar\'\nbaz\n'

不可能通过查看s1和{}的值来区分它们:s1 == s2是真的,repr(s1) == repr(s2)也是。Python解释器甚至可以将它们内接为相同的值,因此它可以根据细节(例如代码是作为一个模块在REPL或imported运行)使^{(或者可能不)为id(s1) == id(s2)为真。在

FWIW,我的理解是有一个约定,其中,'',''''''用于docstring,这有点像一个注释,但它是一个可重新调用的属性,以后可以引用。https://www.python.org/dev/peps/pep-0257/

我也是个初学者,但我的理解是对字符串使用三重引号并不是最好的主意,即使如果与您当前所做的功能几乎没有区别(我不知道以后是否会有)。遵守约定对其他人阅读和使用您的代码很有帮助,而且如果您不遵循这些约定,一些约定会咬到您,就像在这种情况下,一个格式错误的带有三个引号的字符串将被解释为docstring,并且可能不会抛出错误,您需要搜索一堆找到问题的代码。在

相关问题 更多 >