Python here document

Python here document

When I looked it up in title: python title: Here Document on Qiita, there was only one, so I wrote an article because it wasn't summarized very much! I hope that people who use Python for the first time and those who use Python once in a while will be able to put it together with a sense of level that makes them forget how to write it. If you have any questions, please leave a comment.

version.py


python -V
Python 2.7.13

Final goal

matome.py


import textwrap
string = textwrap.dedent('''
  This is a {what}.
  I'm from {where}.
''').format(what="apple", where="Chiba").strip()
print(string)

"""
This is a apple.
I'm from Chiba.
"""

Contents

What is a here document?

Such
new line
It makes it easier to handle sentences that contain.

sample.py


# \n means line break

#like this\Without writing a lot of n"Surrounding it with × 3 makes it easier to handle.
string = "Such\n line break\It makes it easier to handle sentences with n."

#Here document to write like this(Wind)
string = """
Such
new line
It makes it easier to handle sentences that contain.
"""

Here-documents and multi-line comments

sample.py


# coding: utf-8

#One line comment#With

"""
Multi-line comment"It is × 3.
"""

'''
This is also a multi-line comment
is! !!
'''

The part that is not commented out like this will be a strange color, so please distinguish it.
I get an error here.

When dealing with Japanese, first # coding: utf-8.

Ordinary here document

sample.py



#This is a normal here document

string = '''This is a pen.
I'm from Tokyo.'''

print(string)

#Output result
"""
This is a pen.
I'm from Tokyo.
"""

Compare up and down. It is better to write as follows, but line breaks are added before and after, so I will correct it.

sample.py



string = '''
This is a pen.
I'm from Tokyo.
'''

print(string)

#Output result

"""

This is a pen.
I'm from Tokyo.

"""

#There is a margin at the top and bottom.

How to erase the top and bottom margins

Tips to make Python here-documents easier to read I referred to this article and the comment section.

How to erase the top and bottom margins [1: -1]

sample.py



string = '''
This is a pen.
I'm from Tokyo.
'''[1:-1]

print(string)

#Output result
"""
This is a pen.
I'm from Tokyo.
"""

Let's see how to use [1: -1].

sample.py



print("test123456789"[1:-1])

#Output result
"""
est12345678
"""

How to erase the top and bottom margins strip ()

sample.py



string = '''
This is a pen.
I'm from Tokyo.
'''.strip()

print(string)

#output
This is a pen.
I'm from Tokyo.

strip () removes leading and trailing whitespace characters. Reference article If you omit the argument of [python] strip (), not only spaces but also line breaks are removed

sample.py



print("     space5     ".strip())
print("     \nspace5\n     ".strip())

#Both remove the newline and spaces.
"""
space5
"""

How to erase the top and bottom margins Backslash \

sample.py



string = '''\
This is a pen.
I'm from Tokyo.\
'''

print(string)

#output

"""
This is a pen.
I'm from Tokyo.
"""

Backslash \ is used when you want to start a new line in the middle of Python code, or when you want to make it longer and read better. It looks like a line break, but python ignores the line break and reads it.

print ("te\
st")
print \
  ("test")

"""
test
test
"""

Indent removal

Let's look at deleting the indent of the here document when the indent is low.

if True:
    string = '''
        This is a pen.
        I'm from Tokyo.
        '''.strip()
    print(string)

"""
        This is a pen.
        I'm from Tokyo.     
"""

import textwrap Import this textwrap. This is the easiest.

sample.py



import textwrap

if True:
    string = '''
        This is a pen.
        I'm from Tokyo.
        '''
    print(string)

print (textwrap.dedent(string).strip())

"""
--------
This is a pen.
I'm from Tokyo.
--------
"""

textwrap.dedent (string) will remove the indentation for each line.

Variable expansion

Click here for a very helpful link. Note that I checked the format when expanding variables in a string in Python

sample.py


string = '''
This is a {what}.
I'm from {where}.
'''.format(what="apple", where="Chiba").strip()

print(string)

"""
--------
This is a apple.
I'm from Chiba.
--------
"""

{what} what="apple" I feel like I'll look it up every time I use it, such as adding {} or not enclosing what and "".

Summary

matome.py


import textwrap
string = textwrap.dedent('''
  This is a {what}.
  I'm from {where}.
''').format(what="apple", where="Chiba").strip()
print(string)

"""
This is a apple.
I'm from Chiba.
"""

I've written somehow what I think I'll use in here documents, but I think there are a lot of things missing, but I hope it helps!

Recommended Posts

Python here document
My best here document
python document reading descriptor HowTo
Python
Document Python code with Doxygen
python dict object memorandum (mysterious document)
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
ufo-> python (3)
Python comprehension
install python
Python Singleton
python memo
Python Jinja2
How to write Python document comments (Docstrings)
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
[Python] Sort
HTML document your Python program with Sphinx
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping
Python update (2.6-> 2.7)
python memo
Python # sort
ufo-> python
Python nslookup
python learning
Hannari Python 2020
[Rpmbuild] Python 3.7.3.
Prorate Python (1)
python memorandum