Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22871

Python Morsels: Unindenting multi-line strings in Python

$
0
0

Need a multi-line string but don't want to include a big block of manually dedented text in your Python code? Use textwrap.dedent!

Manually dedenting multi-line strings

Here we have a function that prints out a copyright statement:

defcopyright():print("""\        Copyright (c) 1991-2000 ACME Corp        All Rights Reserved.        Copyright (c) 2000-2030 Cyberdyne        All Rights Reserved.""")
defcopyright():print("""\        Copyright (c) 1991-2000 ACME Corp        All Rights Reserved.        Copyright (c) 2000-2030 Cyberdyne        All Rights Reserved.""")

This function works, but the copyright statement that it prints out is indented:

>>> copyright()        Copyright (c) 1991-2000 ACME Corp        All Rights Reserved.        Copyright (c) 2000-2030 Cyberdyne        All Rights Reserved.
>>> copyright()        Copyright (c) 1991-2000 ACME Corp        All Rights Reserved.        Copyright (c) 2000-2030 Cyberdyne        All Rights Reserved.

Each line in this copyright statement begins with eight spaces. This happens because in our code, the text within our string begins with eight spaces before each line.

We can fix this problem by manually dedenting the text within this string:

defcopyright():print("""\Copyright (c) 1991-2000 ACME CorpAll Rights Reserved.Copyright (c) 2000-2030 CyberdyneAll Rights Reserved.""")
defcopyright():print("""\Copyright (c) 1991-2000 ACME CorpAll Rights Reserved.Copyright (c) 2000-2030 CyberdyneAll Rights Reserved.""")

While this does work:

>>> copyright()Copyright (c) 1991-2000 ACME CorpAll Rights Reserved.Copyright (c) 2000-2030 CyberdyneAll Rights Reserved.
>>> copyright()Copyright (c) 1991-2000 ACME CorpAll Rights Reserved.Copyright (c) 2000-2030 CyberdyneAll Rights Reserved.

This also makes our code a bit tricky to read.

Our code is less readable than before because up here, we our code suddenly dedents in the middle of our string.

We could fix this problem in by using the dedent function in Python's textwrap module.

Using textwrap.dedent to unindent strings

The dedent function allows us …

Read the full article: https://www.pythonmorsels.com/dedent/


Viewing all articles
Browse latest Browse all 22871

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>