62

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?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Estarius
  • 1,219
  • 3
  • 13
  • 24
  • With all these answers, I realized that one of my main issue with this was the comparison of normal strings with string literal. If I understood well, the major difference is that normal string are associated to a variable while string literal are more "floating" ? – Estarius May 31 '12 at 20:05
  • 2
    https://www.google.ca/search?q=define%3A"string+literal" Seriously, Google is much more powerful than people give it credit for. – Karl Knechtel May 31 '12 at 23:32
  • Actually, *any* statement in a function can be a string literal, or a standalone integer, for that matter (2 or 2834329 can be considered an "integer literal"). It is syntactically correct; it just won't be doing anything. As an example of a different convention, if you are programming in Groovy (instead of Python), the value of the last statement will be returned as the return value; so there people sometimes end a function with just e.g. `1` on a separate line. – Sergey Orshanskiy Feb 08 '15 at 22:02
  • String Literal: Well `string` is some text and `literal` maybe as in "take it literally", e.g. don't interpret this as code. – Dennis Kuypers Jan 27 '17 at 09:47

6 Answers6

72

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

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

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.

or

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!

or even

#This can contain line breaks too!  See?
''' triple-single 
    quotes '''
mgilson
  • 300,191
  • 65
  • 633
  • 696
39

Well, it can be helpful to take a look at the concepts of expressions, literals, and strings.

Strings, expressions, and literals

In a program, we have to represent various types of data. One type of data is integer numbers; another type is floating-point numbers.

A value of some type can be yielded in various ways, i.e., through various expressions. An expression is any snippet of a program that "creates" a value. For example, in the Python expression below, the expression 2+2 yields the value 4. The assignment operator = puts the yielded value 4 in a variable named i:

i = 2+2

Given the statement above, the expression below yields the same value 4, but now this expression contains only a variable:

i

Below, we yielded a value by an arithmetic expression, and then yielded it by a variable (which is also an expression).

Languages, however, should provide a syntax to yield basic values directly. For example, the 2 in the expression above retrieves the value 2. Expressions that yield basic values directly are called literals. Both expressions 2+2 and 4 yield the same value, 4, but the second expression is a very basic way to represent the operation, provided by the language, with no need of executing an explicit operation, so it is a literal.

String literals and multiline strings

A very important type of data is text, a sequence of letters, digits, and other characters. This type is usually called string.

A string literal, in this way, is a literal that yields a string. In Python, those literals are marked by many ways (i.e, there are many syntaxes for string literals). You can for example put a single or double quote at either the beginning or the end of the literal:

"A string literal"

'Another string literal'

Other ways are to put three single or double quotes in the same positions. In this case, the literal can span through multiple lines:

"""A single line string literal"""

"""A multiline
string literal"""

'''Another multiline
string literal'''

Note that whatever syntax you choose to a string literal, it does not change its value. A single-quoted string is equal to a double-quoted string with the same characters, and a three-quote string is equal to a one-quote string with the same content:

>>> "A single line string literal" == 'A single-line string literal'
True

>>> """A single line string literal""" == "A single line string literal"
True

>>> # \n is the character that represents a new line
>>> "A multiline\nstring literal" == """A multiline
string literal""" 
True

Docstrings and why should they be string literals

What the documentation is saying is that you can put a string literal just after the method declaration and this literal will be used as documentation - what we use to call a docstring. It does not matter if you use single- or double-quoted strings, or one- or three-quote strings either: it just needs to be a literal.

Consider the functions below:

def f1(value):
    "Doc for f1"
    return value + 1

def f2(value):
    """Doc for f2"""
    return value + 2

Now, declare them in your python console and call help(f1) and help(f2). Note that the syntax of the string literal does not matter.

OTOH, you cannot use other expressions, such as variables or operations over strings, for generating your documentation. So the strings at the first line of the functions below are no docstring:

mydoc = "This is doc"
def f3(value):
     mydoc
     return value+3

 def f4(value):
     "This is no documentation " + "because it is concatenated"
     return value+4

It should be a literal because the compiler was written explicitly to manage it as documentation. However, the compiler is not prepared to manage variables, complex expressions, etc. as documentation, so it will ignore them. In other words, it is by design.

Why use triple quote strings as docstrings?

Although any form of string literal can be used in docstrings, you may consider that documentation usually includes very long texts, with multiple lines and paragraphs. Well, since it includes many lines, better to use the literal forms which accept multiple lines, right? This is the reason why triple-quote strings are the preferred (but not mandatory) way of writing docstrings.

A marginal note

Actually, you can put a string literal in any place of a Python function:

 def flying_literals(param):
    "Oh, see, a string literal!"
    param += 2
    "Oh, see, ANOTHER string literal!"
    return param
    "the above literal is irrelevant, but this one can be still MORE IRRELEVANT"

However, only the literal in the first line makes some difference (being the documentation). The other ones are no-ops.

brandizzi
  • 26,083
  • 8
  • 103
  • 158
  • 2
    Sorry for such comment, but this is one of the most comprehensive and complete answers to this topic. The marginal note was what I was looking for. Thanks! – David Ferenczy Rogožan Jan 26 '17 at 13:44
  • Some features of the many kinds of strings are worth noting: single quotes need not be escaped in strings enclosed in single double quotes: `"foo 'bar' baz"`. Single quotes must be escaped in strings enclosed in single single quotes: `'foo \'bar\' baz'`. Single quotes need not be escaped in strings enclosed in triple single quotes: `'''foo 'bar' baz'''`. And so on. Play with all the combinations in a Python REPL and you'll get the idea quickly. The combinations include enclosing single single, single double, triple single, triple double, and internal non-escaped and escaped single and double. – Reb.Cabin Jul 07 '17 at 01:25
8

A string literal is simply a string given literally in the source code. Whether it is a docstring or another string does not matter. See the Python language documentation section on string literals for all the details, but you probably don't need these details now.

A few examples:

"abc"
'Guido'
r"""Norwegian Blue"""
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
7

A string literal is a string in one of the many quoting options, that is not assigned to a variable.

So,

"String" # string literal
'string' # string literal
"""
  Multiline
  String
  Literal
"""
foo = "string variable"

When you have a string literal immediately after a def block, it becomes part of the documentation for that method, and is called a docstring

def foo(hello):
    """This is part of the documentation for foo"""

This is how you would use it:

>>> def foo(hello):
...     """This is the docstring"""
...     pass
... 
>>> foo.__doc__
'This is the docstring'
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
5

In Python there are several ways to divide strings into multiple lines. Strings literals is one of them, for example:

s = """Hello,
    world"""
print(s)
>>> Hello,
>>>     world #Notice, that spaces used in the literal are kept.

But as you noticed correctly, string literals are usually there for the in-line documentation

class MyClass(object):
    """This is my class it does this and that.

       It has some cool features and I may tell you about them below.
    """

    def my_method(self):
        """This is a brief description of my method."""

    def important_method(self):
        """Because this method is important, I'm going to tell you
           a lot about it. For example...
        """

Before you ask, a good way to split strings on multiple lines, are the holy Python parenthesis:

s = ('This is a very very long string. '
     'I have to split it to multiple lines. '
     'Whoa! It works!')
print(s)
>>> This is a very very long string. I have to split it to multiple lines. Whoa! It works!

You may need this to follow the PEP-8, which states that "Thou shalt not exceed 80 characters per line".

Happy Python hacking!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
  • 1
    Upvoting this because it shows example that triple-double quote can also be assigned, not only a docstring. Some people may think triple-double quote can't be used as normal, usual string. – Nuclear03020704 Jun 14 '20 at 14:52
1

They are strings like any other strings with pairs of ', ", ''' or """ around them.
The recommended form is the triple double quote:

def some_function(s):
    """this is documentation for some_function"""
    print(s)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Anthon
  • 69,918
  • 32
  • 186
  • 246