Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Write Better Python Cleaner Code Docstrings

Making a string with new line characters using docstrings?...

Hi!

This part of the video confused me; can someone (Kenneth Love?) please explain what is special about docstrings such that it allows a string with new line characters to be assigned to a variable? I just tried it using only one set of double quotes, and it worked just fine.

Thanks for any clarification! Graham

mark tur
mark tur
6,996 Points

I don't fully understand the question, but that may also be because it's been a little while since I've seen this video. Docstrings are good because it tells other people what the method does. If you add the \n characters in the docstring, you will add a new line in the console. General convention is to write docstrings for every method you create so one does not need to dissect the code to understand what that method does. More information on docstring conventions can be found in PEP 257: https://www.python.org/dev/peps/pep-0257/

Thanks, Mark. It looks like Kenneth meant literal newlines, not the newline character.

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

img

You can't have a string with single or double quotes and a literal new line in it.

Ah, I see. You meant a literal newline, not a \n. Good to know. Thanks for the clarification!

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

A blank line can be added using the newline character \n:

$ python3
Python 3.4.0 (default, Jun 19 2015, 14:20:21) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> """this string
... has a blank line
... 
... in it""" == "this string\nhas a blank line\n\nin it"
True
>>> def func():
...     "This is a\nmult-line\ndocstring using a\nsingle string"
...     pass
... 
>>> func.__doc__
'This is a\nmult-line\ndocstring using a\nsingle string'
>>> help(func)
Help on function func in module __main__:

func()
    This is a
    mult-line
    docstring using a
    single string

This is a demonstration of what is possible. It is not a recommended practice for docstrings.

Thanks, Chris. It looks like Kenneth meant a literal newline, not a newline character.