在函数定义中带有三引号的字符串文字 [英] String literal with triple quotes in function definitions

查看:199
本文介绍了在函数定义中带有三引号的字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Python教程,在某些时候,他们谈论函数的第一条语句如何成为String Literal.就示例而言,此字符串文字似乎是用三个"完成的,并给出了

I am following the Python tutorial and at some point they talk about how the 1st statement of a function can be a String Literal. As far as the example goes, this String Literal seems to be done with three "s, giving in the example

"""Print a Fibonacci series up to n."""

根据本文档,这将主要用于创建某种自动生成的文档.

According to this documentation, this would be used mainly to create some kind of automatically produced documentation.

所以我想知道是否有人可以向我解释这些字符串文字到底是什么?

So I am wondering if someone here could explain to me what are these string literals exactly?

推荐答案

您所说的(我认为)称为

What you're talking about (I think) are called docstrings (Thanks Boud for the link).

def foo():
    """This function does absolutely nothing"""

现在,如果您从解释器中键入help(foo),您将看到我放入函数中的字符串.您也可以通过foo.__doc__

Now, if you type help(foo) from the interpreter, you'll get to see the string that I put in the function. You can also access that string by foo.__doc__

当然,字符串文字就是文字字符串.

Of course, string literals are just that -- literal strings.

a = "This is a string literal"  #the string on the right side is a string literal, "a" is a string variable.

foo("I'm passing this string literal to a function")

可以通过多种方式定义它们:

They can be defined in a bunch of ways:

'single quotes'
"double quotes"
""" triple-double quotes """  #This can contain line breaks!

甚至

#This can contain line breaks too!  See?
''' triple-single 
    quotes '''

这篇关于在函数定义中带有三引号的字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆