<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python &#8211; CFXLOG</title>
	<atom:link href="https://cfxlog.com/category/python/feed/index.xml" rel="self" type="application/rss+xml" />
	<link>https://cfxlog.com/</link>
	<description></description>
	<lastBuildDate>Wed, 11 Nov 2026 22:25:16 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.4</generator>

<image>
	<url>https://cfxlog.com/wp-content/uploads/2026/07/cfxlog-favicon-150x150.png</url>
	<title>Python &#8211; CFXLOG</title>
	<link>https://cfxlog.com/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】正規表現の使い方と知ってると便利なテクニック</title>
		<link>https://cfxlog.com/python-re/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Mon, 17 Aug 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5254</guid>

					<description><![CDATA[このような方に向けて、Python の正規表現テクニックをお伝えします。 正規表現は、文字列データから特定のパターンを検索するために使われるツールです。 応用範囲は広く、以下のような多岐にわたる作業を一瞬で片付けることが [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-group is-style-crease"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>Python で高度な文字列操作を行いたい！</li>
</ul>
</div></div>



<p class="wp-block-paragraph">このような方に向けて、Python の正規表現テクニックをお伝えします。</p>



<p class="wp-block-paragraph">正規表現は、文字列データから特定のパターンを検索するために使われるツールです。</p>



<p class="wp-block-paragraph">応用範囲は広く、以下のような多岐にわたる作業を一瞬で片付けることができます。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>抽出</li>



<li>検索</li>



<li>整形・置き換え</li>
</ul>
</div></div>



<p class="wp-block-paragraph">正規表現をマスターすれば、手作業では絶対にこなせない処理を一瞬で片付けることができます。「プログラミングをやっていてよかった！」と思えるはずです。</p>



<p class="wp-block-paragraph">具体的なメソッドなどをご紹介する前に、正規表現に関する基礎知識をお伝えします。</p>



<p class="wp-block-paragraph">プログラムを組む際に必要な最低限の情報に留めていますので、できれば目を通していただければと思います。</p>



<p class="wp-block-paragraph">正規表現（Regular Expression）は、文字列の規則性を表現する方法です。</p>



<p class="wp-block-paragraph">これにより、元となる文字列データからパターンに一致する文字列部分を見つけたり、置き換えしたりといったことがプログラムを通してできるようになります。</p>



<p class="wp-block-paragraph">正規表現では「文字列の規則性」を表現するため、特殊な意味を持つ記号が用意されています。</p>



<figure class="wp-block-table"><table><thead><tr><th>メタ文字</th><th>意味</th></tr></thead><tbody><tr><td><code>.</code></td><td>任意の一文字</td></tr><tr><td><code>*</code></td><td>直前の文字の0回以上の繰り返し</td></tr><tr><td><code>+</code></td><td>直前の文字の1回以上の繰り返し</td></tr><tr><td><code>?</code></td><td>直前の文字の0回または1回出現</td></tr><tr><td><code>^</code></td><td>文字列の始まり</td></tr><tr><td><code>$</code></td><td>文字列の終わり</td></tr><tr><td><code>[]</code></td><td>かっこ内の任意の単一文字</td></tr><tr><td><code>|</code></td><td>論理和、いずれかのパターン</td></tr><tr><td><code>()</code></td><td>かっこ内をグループとする</td></tr></tbody></table><figcaption class="wp-element-caption">メタ文字の例</figcaption></figure>



<p class="wp-block-paragraph">これだけでは、どのように使うかのイメージがつきにくいですよね。</p>



<p class="wp-block-paragraph">具体的な使い方は、この後に丁寧にお伝えしていきます。</p>



<p class="wp-block-paragraph">Python で正規表現を扱うためには re ライブラリを使います。<br>ここではよく使うメソッドを中心に解説します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>re.search(pattern, string)</li>



<li>re.match(pattern, string)</li>



<li>re.findall(pattern, string)</li>



<li>re.sub(pattern, repl, string)</li>
</ul>
</div></div>



<p class="wp-block-paragraph">順番に解説していきます。</p>



<p class="is-style-icon_announce wp-block-paragraph">メソッドの戻り値である Match オブジェクトの使い方は、後ほど解説します。</p>



<p class="wp-block-paragraph">対象となる文字列から、パターンに一致する最初の箇所を見つけます。</p>



<p class="wp-block-paragraph">一致するパターンがあった場合には Match オブジェクトが、なかった場合には None が返ってきます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# パターンと検索対象の文字列を定義
pattern = "python"
text = "I love python code!"

# パターンを検索
match = re.search(pattern, text)

# 結果の表示
if match:
    print("一致が見つかりました:", match.group())
else:
    print("一致が見つかりませんでした。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンと検索対象の文字列を定義</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #CE9178">&quot;python&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;I love python code!&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンを検索</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.search(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 結果の表示</span></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりました:&quot;</span><span style="color: #D4D4D4">, match.group())</span></span>
<span class="line"><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりませんでした。&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">文字列の先頭が、指定したパターンに一致するかを検証します。</p>



<p class="wp-block-paragraph">一致する場合には Match オブジェクトを返し、一致しない場合には None を返します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# パターンと検索対象の文字列を定義
pattern = "Python"
text = "Python, my love, is code!"

# パターンを検索（re.matchを使用）
match = re.match(pattern, text)

# 結果の表示
if match:
    print("一致が見つかりました:", match.group())
else:
    print("一致が見つかりませんでした。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンと検索対象の文字列を定義</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #CE9178">&quot;Python&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;Python, my love, is code!&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンを検索（re.matchを使用）</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.match(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 結果の表示</span></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりました:&quot;</span><span style="color: #D4D4D4">, match.group())</span></span>
<span class="line"><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりませんでした。&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>re.match()</code>関数を使うことにより、直感的に文字列の先頭を判定していることがわかりますのでコードの可読性は向上します。</p>



<p class="wp-block-paragraph">ただ、汎用性という意味においてはre.search()メソッドを使う方が良いかもしれません。正規表現では文字列の先頭を示す<code>^</code>（キャレット）が用意されているので、以下のコードとすることでre.match()と同様の結果を得ることができるからです。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# パターンと検索対象の文字列を定義
pattern = "^Python"
text = "Python, my love, is code!"

# パターンを検索（re.matchを使用）
match = re.search(pattern, text)

# 結果の表示
if match:
    print("一致が見つかりました:", match.group())
else:
    print("一致が見つかりませんでした。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンと検索対象の文字列を定義</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #CE9178">&quot;^Python&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;Python, my love, is code!&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンを検索（re.matchを使用）</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.search(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 結果の表示</span></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりました:&quot;</span><span style="color: #D4D4D4">, match.group())</span></span>
<span class="line"><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりませんでした。&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">この辺りは好みの問題にもなってくるので、個々のプロジェクトに合わせて使い分けてみてください。</p>



<p class="wp-block-paragraph">文字列内のパターンに一致する全ての文字列を探し出し、リストとして返します。</p>



<p class="wp-block-paragraph">以下は文字列内に存在する電子メールアドレスのリストを取得するためのコードです。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# 電子メールアドレスのパターンと検索対象の文字列を定義
pattern = r'\b&#91;A-Za-z0-9._%+-&#93;+@&#91;A-Za-z0-9.-&#93;+\.&#91;A-Z|a-z&#93;{2,}\b'
text = "お問い合わせはsupport@example.comに、またはadmin@example.orgにご連絡ください。"

# パターンに一致する全ての部分文字列を見つける
emails = re.findall(pattern, text)

# 結果を表示する
print("見つかったメールアドレス:", emails)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 電子メールアドレスのパターンと検索対象の文字列を定義</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&apos;\b</span><span style="color: #CE9178">&#91;</span><span style="color: #D16969">A-Za-z0-9._%+-</span><span style="color: #CE9178">&#93;</span><span style="color: #D7BA7D">+</span><span style="color: #D16969">@</span><span style="color: #CE9178">&#91;</span><span style="color: #D16969">A-Za-z0-9.-</span><span style="color: #CE9178">&#93;</span><span style="color: #D7BA7D">+\.</span><span style="color: #CE9178">&#91;</span><span style="color: #D16969">A-Z|a-z</span><span style="color: #CE9178">&#93;</span><span style="color: #D7BA7D">{2,}</span><span style="color: #D16969">\b&apos;</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;お問い合わせはsupport@example.comに、またはadmin@example.orgにご連絡ください。&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンに一致する全ての部分文字列を見つける</span></span>
<span class="line"><span style="color: #D4D4D4">emails = re.findall(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 結果を表示する</span></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;見つかったメールアドレス:&quot;</span><span style="color: #D4D4D4">, emails)</span></span></code></pre></div>



<p class="wp-block-paragraph">実務的には余分なスペース・改行・タブなどを削除してから<code>re.findall()</code>メソッドを実行することが多いです。<br>その場合は、以下のように<code>split()</code>メソッドを実行する形になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 検索対象の文字列（改行やタブが混じっている例）
text = "お問い合わせは\nsupport@example.com\tに、またはadmin@example.orgにご連絡ください。"

# スペース・タブ・改行などを取り除いて1行の文字列に戻す
text = " ".join(text.split())</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># 検索対象の文字列（改行やタブが混じっている例）</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;お問い合わせは</span><span style="color: #D7BA7D">\n</span><span style="color: #CE9178">support@example.com</span><span style="color: #D7BA7D">\t</span><span style="color: #CE9178">に、またはadmin@example.orgにご連絡ください。&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># スペース・タブ・改行などを取り除いて1行の文字列に戻す</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot; &quot;</span><span style="color: #D4D4D4">.join(text.split())</span></span></code></pre></div>



<p class="wp-block-paragraph">これにより「余計な文字列が紛れていることによりパターンを見つけられない」という事態を避けることができます。</p>



<p class="wp-block-paragraph">パターンに一致する文字列を、別の文字列に置き換える関数です。</p>



<p class="wp-block-paragraph">Pyhton の組み込み関数に replace がありますが、<code>re.sub()</code>はパターンを使うことでより柔軟に置き換え対象を探しに行くイメージになります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# 検索するパターン
pattern = r"(\d{4})-(\d{2})-(\d{2})"
# 検索対象の文字列
text = "今日の日付は2023-04-20です。明日は2023-04-21です。"
# 置き換え後のパターン: DD/MM/YYYY 形式
repl = r"\3/\2/\1"

# 置換を実行
replaced_text = re.sub(pattern, repl, text)

print("置換前のテキスト:", text)
print("置換後のテキスト:", replaced_text)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 検索するパターン</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{4}</span><span style="color: #CE9178">)</span><span style="color: #D16969">-</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{2}</span><span style="color: #CE9178">)</span><span style="color: #D16969">-</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{2}</span><span style="color: #CE9178">)</span><span style="color: #D16969">&quot;</span></span>
<span class="line"><span style="color: #6A9955"># 検索対象の文字列</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;今日の日付は2023-04-20です。明日は2023-04-21です。&quot;</span></span>
<span class="line"><span style="color: #6A9955"># 置き換え後のパターン: DD/MM/YYYY 形式</span></span>
<span class="line"><span style="color: #D4D4D4">repl = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;</span><span style="color: #569CD6">\3</span><span style="color: #D16969">/</span><span style="color: #569CD6">\2</span><span style="color: #D16969">/</span><span style="color: #569CD6">\1</span><span style="color: #D16969">&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 置換を実行</span></span>
<span class="line"><span style="color: #D4D4D4">replaced_text = re.sub(pattern, repl, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;置換前のテキスト:&quot;</span><span style="color: #D4D4D4">, text)</span></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;置換後のテキスト:&quot;</span><span style="color: #D4D4D4">, replaced_text)</span></span></code></pre></div>



<p class="wp-block-paragraph">上記のコードで行っている作業の流れは以下の通りです。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>「YYYY-MM-DD」形式のパターンを探す</li>



<li>「DD/MM/YYYY」形式に置き換える</li>
</ul>
</div></div>



<p class="wp-block-paragraph">組み込み関数の<code>replace()</code>ではここまで繊細な操作はできません。</p>



<p class="wp-block-paragraph"><code>re.sub()</code>メソッド、とても便利です。</p>



<p class="wp-block-paragraph">re ライブラリの関数を使うと、戻り値として Match オブジェクトが返ってきます。</p>



<p class="wp-block-paragraph">ここではよく使う Match オブジェクトのメソッドを解説します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>group()</li>



<li>groups()</li>



<li>groupdict()</li>



<li>start(), end()</li>



<li>span()</li>
</ul>
</div></div>



<p class="wp-block-paragraph">順番に解説していきます。</p>



<p class="wp-block-paragraph">パターンに一致した部分を取得するメソッドで、引数に数字を渡すと色々な抽出ができます。</p>



<p class="wp-block-paragraph">具体例をご覧いただいた方が直感的に理解いただけると思うので、コード例を以下に示します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# テキストとパターンを定義
text = "今日の日付は2023-04-20です。"
pattern = r'(\d{4})-(\d{2})-(\d{2})'

# パターンに一致する部分を検索
match = re.search(pattern, text)

if match:
    # 全体の一致を表示
    print("全体の一致:", match.group(0))
    
    # キャプチャグループによる一致を表示
    print("年:", match.group(1))
    print("月:", match.group(2))
    print("日:", match.group(3))</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># テキストとパターンを定義</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;今日の日付は2023-04-20です。&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&apos;</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{4}</span><span style="color: #CE9178">)</span><span style="color: #D16969">-</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{2}</span><span style="color: #CE9178">)</span><span style="color: #D16969">-</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{2}</span><span style="color: #CE9178">)</span><span style="color: #D16969">&apos;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンに一致する部分を検索</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.search(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># 全体の一致を表示</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;全体の一致:&quot;</span><span style="color: #D4D4D4">, match.group(</span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">))</span></span>
<span class="line"><span style="color: #D4D4D4">    </span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># キャプチャグループによる一致を表示</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;年:&quot;</span><span style="color: #D4D4D4">, match.group(</span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">))</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;月:&quot;</span><span style="color: #D4D4D4">, match.group(</span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4">))</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;日:&quot;</span><span style="color: #D4D4D4">, match.group(</span><span style="color: #B5CEA8">3</span><span style="color: #D4D4D4">))</span></span></code></pre></div>



<p class="wp-block-paragraph">Match オブジェクトの出力結果は、以下のようになります。</p>



<figure class="wp-block-table"><table><thead><tr><th>コード</th><th>出力結果</th></tr></thead><tbody><tr><td>match.group(0)</td><td>2023-04-20</td></tr><tr><td>match.group(1)</td><td>2023</td></tr><tr><td>match.group(2)</td><td>04</td></tr><tr><td>match.group(3)</td><td>20</td></tr></tbody></table><figcaption class="wp-element-caption">match オブジェクトの出力結果</figcaption></figure>



<p class="wp-block-paragraph">パターンに一致したグループを要素とするタプルを返します。</p>



<p class="wp-block-paragraph">コード例としては以下となります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# テキストとパターンを定義
text = "今日の日付は2023-04-20です。"
pattern = r'(\d{4})-(\d{2})-(\d{2})'

# パターンに一致する部分を検索
match = re.search(pattern, text)

if match:
    # groups()メソッドを使用してすべてのキャプチャグループを取得
    year, month, day = match.groups()
    
    print(f"年: {year}, 月: {month}, 日: {day}")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># テキストとパターンを定義</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;今日の日付は2023-04-20です。&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&apos;</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{4}</span><span style="color: #CE9178">)</span><span style="color: #D16969">-</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{2}</span><span style="color: #CE9178">)</span><span style="color: #D16969">-</span><span style="color: #CE9178">(</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{2}</span><span style="color: #CE9178">)</span><span style="color: #D16969">&apos;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンに一致する部分を検索</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.search(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># groups()メソッドを使用してすべてのキャプチャグループを取得</span></span>
<span class="line"><span style="color: #D4D4D4">    year, month, day = match.groups()</span></span>
<span class="line"><span style="color: #D4D4D4">    </span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #569CD6">f</span><span style="color: #CE9178">&quot;年: </span><span style="color: #569CD6">{</span><span style="color: #D4D4D4">year</span><span style="color: #569CD6">}</span><span style="color: #CE9178">, 月: </span><span style="color: #569CD6">{</span><span style="color: #D4D4D4">month</span><span style="color: #569CD6">}</span><span style="color: #CE9178">, 日: </span><span style="color: #569CD6">{</span><span style="color: #D4D4D4">day</span><span style="color: #569CD6">}</span><span style="color: #CE9178">&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">正規表現として<code>(\d{4})-(\d{2})-(\d{2})</code>を指定しているので、左から順番にタプルの要素として追加されていくイメージです。</p>



<p class="wp-block-paragraph">得られるる Match オブジェクトの内容を表にまとめると以下の通り。</p>



<figure class="wp-block-table"><table><thead><tr><th>コード</th><th>出力結果</th></tr></thead><tbody><tr><td>match.groups()[0]</td><td>2023</td></tr><tr><td>match.groups()[1]</td><td>04</td></tr><tr><td>match.groups()[2]</td><td>20</td></tr></tbody></table><figcaption class="wp-element-caption">match オブジェクトの出力結果</figcaption></figure>



<p class="wp-block-paragraph">得られる Match オブジェクトはタプルとして得られるので、先ほどのコード例のようにアンパッキングでスマートに記述できるのが大きなメリットになります。</p>



<p class="is-style-icon_info wp-block-paragraph"><code>group(0)</code>として得られた文字列全体の取得はできないので、注意が必要です。</p>



<p class="wp-block-paragraph">これまで見てきた方法では、グループの位置を番号で指定して読み出す必要がありました。</p>



<p class="wp-block-paragraph">ところが今回の<code>groupdict()</code>メソッドを使うことでインデックス番号の代わりに辞書のキーを指定することができます。</p>



<p class="wp-block-paragraph">つまり、Match オブジェクトから情報取得するのに「あらかじめつけたラベル（辞書のキー）」で操作できることになります。</p>



<p class="wp-block-paragraph">具体的なコード例を以下の示します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# テキストとパターンを定義
text = "今日の日付は2023-04-20です。"
pattern = r"(?P&lt;year>\d{4})-(?P&lt;month>\d{2})-(?P&lt;day>\d{2})"

# パターンに一致する部分を検索
match = re.search(pattern, text)

if match:
    # groupdict()メソッドを使用して名前付きキャプチャグループの情報を取得
    date_info = match.groupdict()
    
    print(f"年: {date_info&#91;'year'&#93;}, 月: {date_info&#91;'month'&#93;}, 日: {date_info&#91;'day'&#93;}")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># テキストとパターンを定義</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;今日の日付は2023-04-20です。&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;</span><span style="color: #CE9178">(</span><span style="color: #569CD6">?P&lt;year&gt;</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{4}</span><span style="color: #CE9178">)</span><span style="color: #D16969">-</span><span style="color: #CE9178">(</span><span style="color: #569CD6">?P&lt;month&gt;</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{2}</span><span style="color: #CE9178">)</span><span style="color: #D16969">-</span><span style="color: #CE9178">(</span><span style="color: #569CD6">?P&lt;day&gt;</span><span style="color: #D16969">\d</span><span style="color: #D7BA7D">{2}</span><span style="color: #CE9178">)</span><span style="color: #D16969">&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンに一致する部分を検索</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.search(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># groupdict()メソッドを使用して名前付きキャプチャグループの情報を取得</span></span>
<span class="line"><span style="color: #D4D4D4">    date_info = match.groupdict()</span></span>
<span class="line"><span style="color: #D4D4D4">    </span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #569CD6">f</span><span style="color: #CE9178">&quot;年: </span><span style="color: #569CD6">{</span><span style="color: #D4D4D4">date_info&#91;</span><span style="color: #CE9178">&apos;year&apos;</span><span style="color: #D4D4D4">&#93;</span><span style="color: #569CD6">}</span><span style="color: #CE9178">, 月: </span><span style="color: #569CD6">{</span><span style="color: #D4D4D4">date_info&#91;</span><span style="color: #CE9178">&apos;month&apos;</span><span style="color: #D4D4D4">&#93;</span><span style="color: #569CD6">}</span><span style="color: #CE9178">, 日: </span><span style="color: #569CD6">{</span><span style="color: #D4D4D4">date_info&#91;</span><span style="color: #CE9178">&apos;day&apos;</span><span style="color: #D4D4D4">&#93;</span><span style="color: #569CD6">}</span><span style="color: #CE9178">&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">コード例で示した通り、パターンの前に<code>?P&lt;key&gt;</code>を追加するだけでOKです。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>(?P&lt;key>pattern)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">(</span><span style="color: #F44747">?</span><span style="color: #D4D4D4">P&lt;key&gt;pattern)</span></span></code></pre></div>



<p class="is-style-icon_announce wp-block-paragraph">余談ですが、この<code>?P&lt;key&gt;</code>という構文は Django の urls.py で正規表現を使ったルーティングをする場合にも使われます。</p>



<p class="wp-block-paragraph"><code>start()</code>と<code>end()</code>は検索対象の文字列の中で、マッチした文字列の「最初の文字のインデックス番号」と「最後の文字のインデックス番号」を取得できます。</p>



<p class="wp-block-paragraph">以下は “example” という文字列を検索対象として、”amp” というパターンを探した例です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


# テキストとパターンを定義
text = "example"
pattern = "amp"

# パターンに一致する部分を検索
match = re.search(pattern, text)

if match:
    # 一致の開始位置と終了位置
    print("一致の開始位置:", match.start())
    print("一致の終了位置:", match.end())
else:
    print("一致が見つかりませんでした。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># テキストとパターンを定義</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;example&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #CE9178">&quot;amp&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンに一致する部分を検索</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.search(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># 一致の開始位置と終了位置</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致の開始位置:&quot;</span><span style="color: #D4D4D4">, match.start())</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致の終了位置:&quot;</span><span style="color: #D4D4D4">, match.end())</span></span>
<span class="line"><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりませんでした。&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">print() 関数の結果は、以下となります。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>一致の開始位置: 2</li>



<li>一致の終了位置: 5</li>
</ul>
</div></div>



<p class="wp-block-paragraph">最初の文字のインデックス番号を0として、何番目に対象の文字があるかを判断します。</p>



<p class="wp-block-paragraph">今回の例では “amp” という文字の塊を検索していますから、以下のように文字の順番を取得してきています。</p>



<figure class="wp-block-table"><table><thead><tr><th>メソッド</th><th>対象文字</th><th>インデックス番号</th></tr></thead><tbody><tr><td>match.start()</td><td>a</td><td>2</td></tr><tr><td>match.end()</td><td>p</td><td>5</td></tr></tbody></table><figcaption class="wp-element-caption">match オブジェクトの出力結果</figcaption></figure>



<p class="wp-block-paragraph">ここで得られた番号は、例えば特定の単語の前後にある文脈を取得する際などに使えます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


text = "This is an example. This example is interesting."
pattern = "example"

# パターンに一致する部分を検索
for match in re.finditer(pattern, text):
    # 一致の前後10文字を取得して表示
    # 開始位置が負の値にならないようにする
    start = max(match.start() - 10, 0)
    # 終了位置の後の10文字を取得
    end = match.end() + 10

    context = text&#91;start:end&#93;
    print(f"一致のコンテキスト: '{context}'")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;This is an example. This example is interesting.&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #CE9178">&quot;example&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンに一致する部分を検索</span></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> match </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> re.finditer(pattern, text):</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># 一致の前後10文字を取得して表示</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># 開始位置が負の値にならないようにする</span></span>
<span class="line"><span style="color: #D4D4D4">    start = </span><span style="color: #DCDCAA">max</span><span style="color: #D4D4D4">(match.start() - </span><span style="color: #B5CEA8">10</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">)</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># 終了位置の後の10文字を取得</span></span>
<span class="line"><span style="color: #D4D4D4">    end = match.end() + </span><span style="color: #B5CEA8">10</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    context = text&#91;start:end&#93;</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #569CD6">f</span><span style="color: #CE9178">&quot;一致のコンテキスト: &apos;</span><span style="color: #569CD6">{</span><span style="color: #D4D4D4">context</span><span style="color: #569CD6">}</span><span style="color: #CE9178">&apos;&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">テキストデータの処理や分析など、柔軟に行う際に有効です。</p>



<p class="wp-block-paragraph"><code>start()</code>と<code>end()</code>を同時に取得したい場合は、両方とも一度に取得できる<code>span()</code>メソッドを使うのが便利です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re

# テキストとパターンを定義
text = "example"
pattern = "amp"

# パターンに一致する部分を検索
match = re.search(pattern, text)

if match:
    # span()を使用して一致の開始位置と終了位置を取得
    start, end = match.span()
    print("一致の開始位置:", start)
    print("一致の終了位置:", end)
else:
    print("一致が見つかりませんでした。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># テキストとパターンを定義</span></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;example&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #CE9178">&quot;amp&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># パターンに一致する部分を検索</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.search(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #6A9955"># span()を使用して一致の開始位置と終了位置を取得</span></span>
<span class="line"><span style="color: #D4D4D4">    start, end = match.span()</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致の開始位置:&quot;</span><span style="color: #D4D4D4">, start)</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致の終了位置:&quot;</span><span style="color: #D4D4D4">, end)</span></span>
<span class="line"><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりませんでした。&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>match.span()</code>で得られるタプルをアンパッキングして、start, end で受け取っている形です。</p>



<p class="wp-block-paragraph">正規表現を使う場合には、検索対象の文字列が膨大になる場合があります。</p>



<p class="wp-block-paragraph">そうなると、できるだけパフォーマンスを落とさないようなコーディングを行うことが重要。</p>



<p class="wp-block-paragraph">ここからは Python の re ライブラリのパフォーマンスアップに役立つヒントをお伝えしていきます。</p>



<p class="wp-block-paragraph">同じパターンを何度も使う場合、パターンをコンパイルすることでパフォーマンスアップが期待できます。</p>



<p class="wp-block-paragraph">コンパイルには<code>re.compile()</code>メソッドを使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


pattern = re.compile(r"\bexample\b")
matches = pattern.findall("This is an example.")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">pattern = re.compile(</span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;\bexample\b&quot;</span><span style="color: #D4D4D4">)</span></span>
<span class="line"><span style="color: #D4D4D4">matches = pattern.findall(</span><span style="color: #CE9178">&quot;This is an example.&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">つまり「正規表現パターンから<code>re</code>オブジェクトに変換する作業（つまりコンパイル）」を一度で済ますことにより、同じことを繰り返すことを避けることができるのでパフォーマンスアップが期待できるということになります。</p>



<p class="wp-block-paragraph">キャプチャグループとは、()の中を一つのグループとして後から各グループを参照したりできるようにするものです。</p>



<p class="wp-block-paragraph">もしも「パターンにマッチしているかだけが知りたい」場合で、ヒットした具体的な文字列は関係ない場合、具体的な文字列を記憶しておく分だけリソースを使ってしまうことになります。</p>



<p class="wp-block-paragraph">そのような場合に便利なのが、<code>(?:)</code>という記法です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># キャプチャグループを使用
pattern = re.compile(r"(example)")

# 非キャプチャグループを使用
pattern = re.compile(r"(?:example)")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># キャプチャグループを使用</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = re.compile(</span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;</span><span style="color: #CE9178">(</span><span style="color: #D16969">example</span><span style="color: #CE9178">)</span><span style="color: #D16969">&quot;</span><span style="color: #D4D4D4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 非キャプチャグループを使用</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = re.compile(</span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;</span><span style="color: #CE9178">(?:</span><span style="color: #D16969">example</span><span style="color: #CE9178">)</span><span style="color: #D16969">&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">一つ目のパターンではexampleという文字列を記憶しますが、二つ目のパターンではマッチしているかどうかのみを記憶するのでexampleという具体的な文字列は記憶しません。</p>



<p class="wp-block-paragraph">パターンオブジェクトの内容を最低限に抑えることによって、多少のパフォーマンスアップが望めるということになります。</p>



<p class="wp-block-paragraph">正規表現では、できるだけ多くの文字列にヒットさせる「最大一致量子子（Greedy Quantifiers）」と、できるだけ少ない文字列にヒットさせようとする「最小一致量子子（Non-Greedy or Lazy Quantifiers）」の二つがあります。</p>



<p class="wp-block-paragraph">メタ文字で言うと、以下のような分類です。</p>



<figure class="wp-block-table"><table><thead><tr><th>量子子</th><th>メタ文字の例</th></tr></thead><tbody><tr><td>最大一致量子子</td><td><code>*</code>や<code>+</code>など</td></tr><tr><td>最小一致量子子</td><td><code>*?</code>や<code>+?</code>など</td></tr></tbody></table><figcaption class="wp-element-caption">量子子とメタ文字の関係</figcaption></figure>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 最大一致
pattern = re.compile(r"&lt;.*>")

# 最小一致
pattern = re.compile(r"&lt;.*?>")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># 最大一致</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = re.compile(</span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;&lt;.</span><span style="color: #D7BA7D">*</span><span style="color: #D16969">&gt;&quot;</span><span style="color: #D4D4D4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 最小一致</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = re.compile(</span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;&lt;.</span><span style="color: #D7BA7D">*?</span><span style="color: #D16969">&gt;&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">最大一致量子子を使ってしまうと、パターンを見つける際に大量の不要なマッチング検索を行うことになってしまいます。</p>



<p class="wp-block-paragraph">極力不要なマッチング検索を行わずにパフォーマンスを上げるため、最小一致量子子が推奨されます。</p>



<p class="wp-block-paragraph">正規表現が文字列の先頭や末尾からの一致を調べるときには、<code>^</code>や<code>$</code>を使用しましょう。</p>



<p class="wp-block-paragraph">これにより、検索範囲が限定されて不要な検索を省略できます。</p>



<p class="wp-block-paragraph"><code>.</code>を使うと「任意の1文字に一致」という意味になり便利です。</p>



<p class="wp-block-paragraph">ところが、これでは検索の際に選択肢が多すぎて検索すべきパターンが大量に存在することになります。</p>



<p class="wp-block-paragraph">対策として、<code>[a-zA-Z]</code>などの「できる限り具体的な文字セット」を使用することで、検索範囲が限定されパフォーマンスが向上します。</p>



<p class="wp-block-paragraph">ここまでで Python を使った正規表現テクニックは十分なレベルに達していると思いますが、ここからは「さらに一歩進んだアドバンス的な内容」をご紹介します。</p>



<p class="wp-block-paragraph">目視では煩雑になってしまうので、積極的にツールを使いましょう。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ol class="wp-block-list">
<li><strong>Regex101：</strong>
<ul class="wp-block-list">
<li>ウェブベースの正規表現テスターで、リアルタイムでマッチング結果を確認できます。</li>
<li>Pythonの他、JavaScript、PHP、Goの正規表現もサポートしています。</li>
<li>正規表現の各部分についての詳細な説明が表示され、学習ツールとしても優れています。</li>
<li>URL: <a href="https://regex101.com/">https://regex101.com/</a></li>
</ul>
</li>



<li><strong>RegExr：</strong>
<ul class="wp-block-list">
<li>ウェブベースの別の強力な正規表現テストツールです。</li>
<li>正規表現のパターンにマッチするテキストのハイライト表示、正規表現の部分ごとの説明などの機能を提供します。</li>
<li>URL: <a href="https://regexr.com/">https://regexr.com/</a></li>
</ul>
</li>



<li><strong>Pythex：</strong>
<ul class="wp-block-list">
<li>Pythonの正規表現に特化したシンプルなオンラインテスターです。</li>
<li>リアルタイムでのマッチング結果表示機能を提供し、簡単に正規表現を試すことができます。</li>
<li>URL: <a href="https://pythex.org/">https://pythex.org/</a></li>
</ul>
</li>
</ol>
</div></div>



<p class="wp-block-paragraph">パターンマッチングさせるための正規表現の例を二つほど挙げます。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>携帯電話番号</li>



<li>メールアドレス</li>
</ul>
</div></div>



<p class="wp-block-paragraph">現在では ChatGPT などに条件を教えれば正規表現を組んでくれますので、生成系 AI もフルに活用して対応してみてください。</p>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset5 animation-fade rtoc_open default" data-id="5254" data-theme="SWELL CHILD">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-1">携帯電話番号</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-2">メールアドレス</a></li></ul></li><li class="rtoc-item"><a href="#flag">フラグの使用</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-4">大文字・小文字の無視</a></li><li class="rtoc-item"><a href="#rtoc-5">複数行モードの有効化</a></li><li class="rtoc-item"><a href="#rtoc-6">ドットが改行にもマッチするようにする</a></li><li class="rtoc-item"><a href="#rtoc-7">肯定的先読み</a></li><li class="rtoc-item"><a href="#rtoc-8">否定的先読み</a></li><li class="rtoc-item"><a href="#rtoc-9">肯定後読み</a></li><li class="rtoc-item"><a href="#rtoc-10">否定的後読み</a></li></ul></li></ol></div><h3 id="rtoc-1"  class="wp-block-heading">携帯電話番号</h3>



<p class="wp-block-paragraph">正規表現としては、以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>mobile_phone_no = r"0&#91;789&#93;0-\d{4}-\d{4}"</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">mobile_phone_no = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;0</span><span style="color: #CE9178">&#91;</span><span style="color: #D16969">789</span><span style="color: #CE9178">&#93;</span><span style="color: #D16969">0-\d</span><span style="color: #D7BA7D">{4}</span><span style="color: #D16969">-\d</span><span style="color: #D7BA7D">{4}</span><span style="color: #D16969">&quot;</span></span></code></pre></div>



<p class="wp-block-paragraph">以下に要素を分解して解説します。</p>



<figure class="wp-block-table"><table><thead><tr><th>正規表現</th><th>内容</th></tr></thead><tbody><tr><td>0</td><td>数字の “0” から始まる</td></tr><tr><td>[789]</td><td>キャリアコードの2桁目が “7, 8, 9” である</td></tr><tr><td>0</td><td>キャリアコードの3桁目が “0” である</td></tr><tr><td>-\d{4}</td><td>ハイフンに続いて4桁の数字がある</td></tr><tr><td>-\d{4}</td><td>再びハイフンに続いて4桁の数字がある</td></tr></tbody></table><figcaption class="wp-element-caption">携帯電話番号の正規表現</figcaption></figure>



<h3 id="rtoc-2"  class="wp-block-heading">メールアドレス</h3>



<p class="wp-block-paragraph">基本的な正規表現を示すと、以下のとおりです。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>mail_address = r"&#91;a-zA-Z0-9._%+-&#93;+@&#91;a-zA-Z0-9.-&#93;+\.&#91;a-zA-Z&#93;{2,}"</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">mail_address = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;</span><span style="color: #CE9178">&#91;</span><span style="color: #D16969">a-zA-Z0-9._%+-</span><span style="color: #CE9178">&#93;</span><span style="color: #D7BA7D">+</span><span style="color: #D16969">@</span><span style="color: #CE9178">&#91;</span><span style="color: #D16969">a-zA-Z0-9.-</span><span style="color: #CE9178">&#93;</span><span style="color: #D7BA7D">+\.</span><span style="color: #CE9178">&#91;</span><span style="color: #D16969">a-zA-Z</span><span style="color: #CE9178">&#93;</span><span style="color: #D7BA7D">{2,}</span><span style="color: #D16969">&quot;</span></span></code></pre></div>



<p class="wp-block-paragraph">要素分解すると、以下のようになります。</p>



<figure class="wp-block-table"><table><thead><tr><th>正規表現</th><th>内容</th></tr></thead><tbody><tr><td>[a-zA-Z0-9._%+-]+</td><td>英数字、ドット、アンダースコア、パーセント、プラス、マイナスが1文字以上続く</td></tr><tr><td>@</td><td>@ 記号に一致</td></tr><tr><td>[a-zA-Z0-9.-]+</td><td>ドメイン名で使用可能な文字列に一致</td></tr><tr><td>.</td><td>. 記号に一致</td></tr><tr><td>[a-zA-Z]{2,}</td><td>TLD で許可される文字列が少なくとも2文字以上続く</td></tr></tbody></table><figcaption class="wp-element-caption">メールアドレスの正規表現</figcaption></figure>



<p class="is-style-icon_info wp-block-paragraph">RFC 5322 に完全準拠するものではないことにご注意ください。</p>



<h2 id="flag" class="wp-block-heading">フラグの使用</h2>



<p class="wp-block-paragraph">re ライブラリでは正規表現の動作を制御する「フラグ」と言うものが用意されています。</p>



<p class="wp-block-paragraph">フラグを利用することで、以下のようなことが可能です。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>大文字・小文字の無視</li>



<li>複数行モードの有効化</li>



<li>ドットが改行にもマッチするようにする</li>
</ul>
</div></div>



<p class="wp-block-paragraph">一つずつ具体的にみていきましょう。</p>



<h3 id="rtoc-4"  class="wp-block-heading">大文字・小文字の無視</h3>



<p class="wp-block-paragraph">大文字・小文字を無視してマッチングを行うには<code>re.IGNORECASE</code> を使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re

text = "This is a Sample text."
pattern = r"sample"

# 大文字小文字を区別せずに検索
match = re.search(pattern, text, re.IGNORECASE)
if match:
    print("一致が見つかりました:", match.group())</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;This is a Sample text.&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;sample&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 大文字小文字を区別せずに検索</span></span>
<span class="line"><span style="color: #D4D4D4">match = re.search(pattern, text, re.IGNORECASE)</span></span>
<span class="line"><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> match:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;一致が見つかりました:&quot;</span><span style="color: #D4D4D4">, match.group())</span></span></code></pre></div>



<p class="wp-block-paragraph">上記のコードでは “Sample” と頭文字が大文字になっていますが、<code>re.search()</code>メソッドの第三引数に<code>re.IGNORECASE</code>としていることからマッチしているとみなされます。</p>



<h3 id="rtoc-5"  class="wp-block-heading">複数行モードの有効化</h3>



<p class="wp-block-paragraph"><code>re.MULTILINE</code>を使うことで、<code>^</code>と<code>$</code>が、文字列の開始や終了だけでなく、各行の開始や終了にもマッチするようになります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re

text = "This is a Sample text."
pattern = r"sample"

# 複数行モードを有効にして、各行の開始でマッチングを試みる
multi_line_text = "start\nstart another"
matches = re.findall(r"^start", multi_line_text, re.MULTILINE)
print("マッチした行の数:", len(matches))</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;This is a Sample text.&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;sample&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># 複数行モードを有効にして、各行の開始でマッチングを試みる</span></span>
<span class="line"><span style="color: #D4D4D4">multi_line_text = </span><span style="color: #CE9178">&quot;start</span><span style="color: #D7BA7D">\n</span><span style="color: #CE9178">start another&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">matches = re.findall(</span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;^start&quot;</span><span style="color: #D4D4D4">, multi_line_text, re.MULTILINE)</span></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;マッチした行の数:&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #DCDCAA">len</span><span style="color: #D4D4D4">(matches))</span></span></code></pre></div>



<p class="wp-block-paragraph">上記では改行コードを挟んで１行目も２行目も “start” で始まっているので、<code>len(matches)</code>は<code>2</code>となります。</p>



<h3 id="rtoc-6"  class="wp-block-heading">ドットが改行にもマッチするようにする</h3>



<p class="wp-block-paragraph"><code>re.DOTALL</code>を使うと、メタ文字<code>.</code>が改行コードにもマッチするようになります。</p>



<p class="wp-block-paragraph">デフォルトでは、<code>.</code>は改行文字を除く任意の単一文字にヒットします。これを拡張するようなフラグになります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re

text = "Hello\nWorld"
pattern = r".+"

# re.DOTALL フラグあり
matches = re.findall(pattern, text, re.DOTALL)
print("re.DOTALL フラグあり:", matches)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;Hello</span><span style="color: #D7BA7D">\n</span><span style="color: #CE9178">World&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;.</span><span style="color: #D7BA7D">+</span><span style="color: #D16969">&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># re.DOTALL フラグあり</span></span>
<span class="line"><span style="color: #D4D4D4">matches = re.findall(pattern, text, re.DOTALL)</span></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;re.DOTALL フラグあり:&quot;</span><span style="color: #D4D4D4">, matches)</span></span></code></pre></div>



<p class="wp-block-paragraph">上記でre.DOTALLをつけない場合には “Hello” にしかマッチしません。</p>



<p class="wp-block-paragraph">久々に正規表現を使うとハマるポイントなので、うまくいかない場合にはこの<code>re.DOTALL</code>を思い出しましょう。</p>



<p class="wp-block-paragraph">以下の事項に気をつけるとよいでしょう。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><strong>最初から複雑なものを作ろうとしない</strong>
<ul class="wp-block-list">
<li>段階的に組んでいくことで、どの部分が期待と違うかわかる</li>
</ul>
</li>



<li><strong>部分的にテスト</strong>
<ul class="wp-block-list">
<li>まずはセクションに分けて個別にテスト</li>
<li>最後に全体を組み合わせる</li>
</ul>
</li>



<li><strong>特殊文字のエスケープを確認</strong>
<ul class="wp-block-list">
<li>特殊文字（<code>.</code>、<code>*</code>、<code>?</code>など）を意識する</li>
<li>リテラルとして使うなら、エスケープされているか確認</li>
</ul>
</li>



<li><strong>フラグを意識する</strong>
<ul class="wp-block-list">
<li><a href="#flag">本記事内のこちらの箇所</a>を確認しましょう</li>
</ul>
</li>
</ul>
</div></div>



<p class="wp-block-paragraph">あるパターンの前後に「特定の文字列」があるかを確認する方法です。</p>



<p class="wp-block-paragraph">細分すると、以下の4パターンに分けられます。</p>



<figure class="wp-block-table"><table><thead><tr><th>種類</th><th>記号</th><th>役割</th></tr></thead><tbody><tr><td>肯定的先読み</td><td><code>(?=パターン)</code></td><td>直後にパターンが存在する位置にマッチ</td></tr><tr><td>否定的先読み</td><td><code>(?!パターン)</code></td><td>直後にパターンが存在しない位置にマッチ</td></tr><tr><td>肯定的後読み</td><td><code>(?&lt;=パターン)</code></td><td>直前にパターンが存在する位置にマッチ</td></tr><tr><td>否定的後読み</td><td><code>(?&lt;!パターン)</code></td><td>直前にパターンが存在しない位置にマッチ</td></tr></tbody></table><figcaption class="wp-element-caption">先読みと後読み</figcaption></figure>



<p class="wp-block-paragraph">サンプルコードを交えて、より突っ込んで解説します。</p>



<h3 id="rtoc-7"  class="wp-block-heading">肯定的先読み</h3>



<p class="wp-block-paragraph">“John” の直後に “Doe” が続いた場合のみ、”John” にマッチします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re


text = "John Doe will attend, but Jane Doe will not."
pattern = r"John(?= Doe)"
matches = re.findall(pattern, text)

print(matches)  # &#91;"John"&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;John Doe will attend, but Jane Doe will not.&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;John</span><span style="color: #D4D4D4">(?=</span><span style="color: #D16969"> Doe</span><span style="color: #D4D4D4">)</span><span style="color: #D16969">&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">matches = re.findall(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(matches)  </span><span style="color: #6A9955"># &#91;&quot;John&quot;&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph">“Jane” にはマッチしません。</p>



<h3 id="rtoc-8"  class="wp-block-heading">否定的先読み</h3>



<p class="wp-block-paragraph">以下の場合は、”Jane” の後に “Doe” が続かない場合のみ、”Jane” にマッチします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re

text = "John Doe will attend, but Jane Doe will not."
pattern = r"Jane(?! Doe)"
matches = re.findall(pattern, text)

print(matches)  # []</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;John Doe will attend, but Jane Doe will not.&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;Jane</span><span style="color: #D4D4D4">(?!</span><span style="color: #D16969"> Doe</span><span style="color: #D4D4D4">)</span><span style="color: #D16969">&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">matches = re.findall(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(matches)  </span><span style="color: #6A9955"># []</span></span></code></pre></div>



<p class="wp-block-paragraph">ところが “Jane” のあとは “Doe” しかないので、ヒットしません。</p>



<h3 id="rtoc-9"  class="wp-block-heading">肯定後読み</h3>



<p class="wp-block-paragraph">“John” の後に “Doe” がくると、”Doe” にマッチします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re

text = "John Doe and Jane Doe"
pattern = r"(?&lt;=John )Doe"
matches = re.findall(pattern, text)

print(matches)  # &#91;'Doe'&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;John Doe and Jane Doe&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;</span><span style="color: #D4D4D4">(?&lt;=</span><span style="color: #D16969">John </span><span style="color: #D4D4D4">)</span><span style="color: #D16969">Doe&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">matches = re.findall(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(matches)  </span><span style="color: #6A9955"># &#91;&apos;Doe&apos;&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph">結果は “Doe” となります。</p>



<h3 id="rtoc-10"  class="wp-block-heading">否定的後読み</h3>



<p class="wp-block-paragraph">“John” の後に “Doe” がこない場合に、”Doe” にマッチします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import re

text = "John Doe and Jane Doe"
pattern = r"(?&lt;!John )Doe"
matches = re.findall(pattern, text)

print(matches)  # &#91;'Doe'&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> re</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;John Doe and Jane Doe&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">pattern = </span><span style="color: #569CD6">r</span><span style="color: #D16969">&quot;</span><span style="color: #D4D4D4">(?&lt;!</span><span style="color: #D16969">John </span><span style="color: #D4D4D4">)</span><span style="color: #D16969">Doe&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">matches = re.findall(pattern, text)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(matches)  </span><span style="color: #6A9955"># &#91;&apos;Doe&apos;&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph">上記では “Jane Doe” の “Doe” がマッチします。</p>



<p class="wp-block-paragraph">複雑な正規表現を利用する場合には「ReDoS（正規表現拒否サービス）攻撃」に気をつける必要があります。</p>



<p class="wp-block-paragraph">ReDoS 攻撃とは、攻撃者が悪意のある文字列を送信して正規表現エンジンを過剰に消費させ、サービスの遅延や停止させるものです。</p>



<p class="wp-block-paragraph">これを防ぐための対策をいくつかご紹介します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><strong>複雑な正規表現は使わない</strong>
<ul class="wp-block-list">
<li>多重量子子を避ける ex) .*</li>
<li>量子子のネストを避ける ex) (a+)+</li>
</ul>
</li>



<li><strong>タイムアウトの設定</strong>
<ul class="wp-block-list">
<li>正規表現エンジンの長時間稼働を防ぐ</li>
<li>処理時間の上限を設定する</li>
</ul>
</li>



<li><strong>入力のサニタイズ</strong>
<ul class="wp-block-list">
<li>正規表現エンジンで値を処理する前に検証する</li>
</ul>
</li>



<li><strong>パフォーマンステスト</strong>
<ul class="wp-block-list">
<li>特定の入力に対する処理時間を確認しておく</li>
</ul>
</li>
</ul>
</div></div>



<p class="wp-block-paragraph">Web アプリケーションを作成する際などには、上記に気をつけてみてください。</p>



<p class="wp-block-paragraph">最後に公式ドキュメントをはじめ、理解の役にたつページをご紹介します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><a href="https://docs.python.org/ja/3/library/re.html">re — 正規表現操作</a></li>



<li><a href="https://docs.python.org/ja/3/howto/regex.html">正規表現 HOWTO</a></li>



<li><a href="https://www-creators.com/tool/regex-checker#google_vignette">正規表現チェッカー</a></li>
</ul>
</div></div>



<p class="wp-block-paragraph">本ブログでは他にも Python に関する情報を発信しています。</p>



<p class="wp-block-paragraph">ぜひ、別記事もご覧になってみてください。</p>



<p class="wp-block-paragraph"><a href="https://cfxlog.com/category/python/">» 参考：CFXLOG – Python 記事の一覧へ</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Python】パッケージ管理ツール pip の使い方</title>
		<link>https://cfxlog.com/python-pip/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Sat, 15 Aug 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[環境構築]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5253</guid>

					<description><![CDATA[Python の魅力の一つが豊富な外部ライブラリやフレームワークの存在です。 これらの外部ライブラリなどをインストールするには「パッケージ管理ツール」が必要であり、その一つが今回紹介する pip です。 Python を [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-group is-style-crease"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>外部ライブラリやフレームワークを使いたい！</li>
</ul>
</div></div>



<p class="wp-block-paragraph">Python の魅力の一つが豊富な外部ライブラリやフレームワークの存在です。</p>



<p class="wp-block-paragraph">これらの外部ライブラリなどをインストールするには「パッケージ管理ツール」が必要であり、その一つが今回紹介する pip です。</p>



<p class="wp-block-paragraph">Python をインストールすると、基本的には pip も一緒にインストールされます。<br/>なので、最も手軽に使えるパッケージ管理ツールといえます。</p>



<p class="wp-block-paragraph">今回はそんな pip の基本的な使い方をご紹介します。</p>




<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset5 animation-fade rtoc_open default" data-id="5253" data-theme="SWELL CHILD">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji mokuji_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">pipの基本コマンド</a></li><li class="rtoc-item"><a href="#rtoc-2">依存性の解決とPoetry</a></li><li class="rtoc-item"><a href="#rtoc-3">pip自体をアップグレードする</a></li><li class="rtoc-item"><a href="#rtoc-4">pipが入っていない場合の対処法</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-5">pip の存在を確認する</a></li><li class="rtoc-item"><a href="#rtoc-6">get-pip.py</a></li><li class="rtoc-item"><a href="#rtoc-7">pip のインストール</a></li></ul></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">pipの基本コマンド</h2>


<p class="wp-block-paragraph">pip を使う際に頻出のコマンドをまとめました。</p>



<p class="wp-block-paragraph">一般的な操作であれば、ここでご紹介するコマンドを覚えておけば十分かと思います。</p>



<p class="wp-block-paragraph">requests ライブラリをインストールする場合は以下です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install requests</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#CE9178"> requests</span></span></code></pre></div>



<p class="wp-block-paragraph">二つ以上のライブラリをインストールする場合には、半角スペースを開けて列挙します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install requests pandas</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#CE9178"> requests</span><span style="color:#CE9178"> pandas</span></span></code></pre></div>



<p class="wp-block-paragraph">バージョンを指定する場合は==に続けてバージョンを指定します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install requests==2.31.0</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#CE9178"> requests==</span><span style="color:#B5CEA8">2.31.0</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>--upgrade pip</code>コマンドを実行することで、最新版にアップデートできます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install --upgrade requests</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#569CD6"> --upgrade</span><span style="color:#CE9178"> requests</span></span></code></pre></div>



<p class="is-style-icon_announce wp-block-paragraph"><code>pip install -U requests</code>としても結果は同じです。</p>



<p class="wp-block-paragraph">requests ライブラリをアンインストールする場合は以下のコマンドになります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip uninstall requests</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> uninstall</span><span style="color:#CE9178"> requests</span></span></code></pre></div>



<p class="wp-block-paragraph">複数ライブラリの削除は、半角スペースを挟んで行います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip uninstall requests pandas</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> uninstall</span><span style="color:#CE9178"> requests</span><span style="color:#CE9178"> pandas</span></span></code></pre></div>



<p class="wp-block-paragraph">インストール済みのパッケージの確認には<code>pip list</code>コマンドを使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip list</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> list</span></span></code></pre></div>



<p class="wp-block-paragraph">現在インストールされているパッケージリストを requirements.txt に書き出すには、以下のコマンドを実行します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip freeze &gt; requirements.txt</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> freeze</span><span style="color:#D4D4D4"> > </span><span style="color:#CE9178">requirements.txt</span></span></code></pre></div>



<p class="wp-block-paragraph">まったく別の環境でインストールしたパッケージを復元したい場合には、以下のコマンドで復元できます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install -r requirements.txt</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#569CD6"> -r</span><span style="color:#CE9178"> requirements.txt</span></span></code></pre></div>



<p class="is-style-icon_announce wp-block-paragraph">単に<code>pip freeze</code>とすると、パッケージのリストがテキストで標準出力されます。<br/>これを<code>&gt; requirements.txt</code>とすることで、テキストをファイルとして出力できるようになります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip check</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> check</span></span></code></pre></div>




<h2 id="rtoc-2"  class="wp-block-heading">依存性の解決とPoetry</h2>


<p class="wp-block-paragraph">ライブラリ A とライブラリ B が共に、ライブラリ C のインストールを要求している場合を考えてみましょう。</p>



<p class="wp-block-paragraph">同じライブラリ C といっても、要求しているバージョンが違う場合があります。<br/>そのような場合には、ライブラリ C のバージョンを開発者が決めうちで指定する必要がある場合があります。</p>



<p class="wp-block-paragraph">これが依存性の解決です。</p>



<p class="wp-block-paragraph">pip にはこの依存性の解決を行う機能がなく、自動で行いたい場合には Poetry などの別のパッケージ管理ツールを使うことになります。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/03/python-poetry-guide-300x158.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/python-poetry-guide/">【Poetry使い方から仮想環境の削除まで】Pythonパッケージ管理の完全ガイド</a>
						<span class="p-blogCard__excerpt">Poetry ってどんなもの？ インストール方法が知りたい 使い方を詳しく教えて欲しい 最近では、pip の代わりに Poetry を導入する Python プロジェクトが増えてきました&#8230;</span>					</div>
				</div>
			</div>
		</div>



<h2 id="rtoc-3"  class="wp-block-heading">pip自体をアップグレードする</h2>


<p class="wp-block-paragraph">外部ライブラリと同様、pip そのものも pip でアップグレードできます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install --upgrade pip</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#569CD6"> --upgrade</span><span style="color:#CE9178"> pip</span></span></code></pre></div>



<p class="is-style-icon_info wp-block-paragraph">pip 自体も pip で管理されています。</p>




<h2 id="rtoc-4"  class="wp-block-heading">pipが入っていない場合の対処法</h2>


<p class="wp-block-paragraph">最新の Python なら pip は自動的にインストールされます。</p>



<p class="wp-block-paragraph">ただし少し古めのバージョンをお使い場合などには、pip が付属していない場合があります。</p>



<p class="wp-block-paragraph">以下、その場合の対応方法をご紹介します。</p>



<h3 id="rtoc-5"  class="wp-block-heading">pip の存在を確認する</h3>



<p class="wp-block-paragraph">まずは、以下のコマンドを実行します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>python -m pip --version</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">python</span><span style="color:#569CD6"> -m</span><span style="color:#CE9178"> pip</span><span style="color:#569CD6"> --version</span></span></code></pre></div>



<p class="wp-block-paragraph">これにより、現在の Python インタープリタに pip があるか確認できます。</p>



<h3 id="rtoc-6"  class="wp-block-heading">get-pip.py</h3>



<p class="wp-block-paragraph">続いて、get-pip.py スクリプトをダウンロードします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>wget https://bootstrap.pypa.io/get-pip.py</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">wget</span><span style="color:#CE9178"> https://bootstrap.pypa.io/get-pip.py</span></span></code></pre></div>



<h3 id="rtoc-7"  class="wp-block-heading">pip のインストール</h3>



<p class="wp-block-paragraph">ダウンロードした get-pip.py スクリプトを実行して、pip をインストールします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>python3 get-pip.py</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">python3</span><span style="color:#CE9178"> get-pip.py</span></span></code></pre></div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Python】リスト内包表記と辞書内包表記を基礎を解説！</title>
		<link>https://cfxlog.com/python-naihohyouki/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Fri, 14 Aug 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5252</guid>

					<description><![CDATA[<p><img src="https://cfxlog.com/wp-content/uploads/2026/08/python-naihohyouki-1024x538.jpg" class="webfeedsFeaturedVisual" /></p>このような疑問にお答えします。 Python では内包表記がごく簡単に書けるため、Python を象徴するものとして挙げられることが多いです。（他の言語では存在はしている） この内包表記ですが、簡潔に書ける一方で初学者は [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img src="https://cfxlog.com/wp-content/uploads/2026/08/python-naihohyouki-1024x538.jpg" class="webfeedsFeaturedVisual" /></p>
<div class="wp-block-group is-style-crease"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>内包表記って書き方がよくわからない…</li>



<li>コードを見ても意味がわからない！</li>
</ul>
</div></div>



<p class="wp-block-paragraph">このような疑問にお答えします。</p>



<p class="wp-block-paragraph">Python では内包表記がごく簡単に書けるため、Python を象徴するものとして挙げられることが多いです。（他の言語では存在はしている）</p>



<p class="wp-block-paragraph">この内包表記ですが、簡潔に書ける一方で初学者は以下のように混乱しがちです。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>内包表記を組み立てられない</li>



<li>内包表記を読んで意味を理解できない</li>
</ul>
</div></div>



<p class="wp-block-paragraph">これらは、内包表記の書き方をしっかりと理解すれば解決できます。</p>



<p class="wp-block-paragraph">本記事では内包表記について丁寧に解説していきますので、不安がある方はぜひじっくりと読み進めてみてください！</p>



<p class="wp-block-paragraph">内包表記は、新たにリストや辞書などを生成するための方法です。</p>



<p class="wp-block-paragraph"><code>for</code>ループと<code>if</code>ステートメントを含むコードを一行（ワンライナー）で書けるのが魅力。</p>



<p class="is-style-icon_info wp-block-paragraph">ただし、あまりにも複雑なロジックは<code>for</code>文で書くことを推奨します。極端に読みづらくなってしまうためです。</p>



<p class="wp-block-paragraph">例えば、次のようなfor文を使ったコードがあったとします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>evens_squared = []
for x in range(10):
    if x % 2 == 0:
        evens_squared.append(x**2)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">evens_squared = []</span></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> x </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">10</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> x % </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> == </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        evens_squared.append(x**</span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">このコードでは0から9までの数字のうち偶数だけを抽出し、要素を二乗してリストに格納していくものになります。</p>



<p class="wp-block-paragraph">これをリスト内包表記で書き換えると、以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>evens_squared = &#91;x**2 for x in range(10) if x % 2 == 0&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">evens_squared = &#91;x**</span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> x </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">10</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> x % </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> == </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph">この段階では意味不明だと思いますが、とにかく「一行で簡潔に書けるのだ！」ということをご理解いただければと思います。</p>



<figure class="wp-block-image size-large"><img alt="" data-aspectratio="1024/538" decoding="async" height="538" src="https://cfxlog.com/wp-content/uploads/2026/07/python-naihohyouki-3-1024x538-1.jpg" width="1024"/></figure>



<p class="wp-block-paragraph">ここからは特定の要素を持つ新たなリストを作成する、リスト内包表記の使い方をご説明します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>リスト内包表記の基本的な書き方</li>



<li>複数の条件を持つリスト内包表記の書き方</li>
</ul>
</div></div>



<p class="wp-block-paragraph">順番にレベルアップしていきますので、順に解説していきます。</p>



<p class="wp-block-paragraph">リスト内包表記の文法は以下のようになります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>new_list = &#91;expression for item in iterable if condition&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">new_list = &#91;expression </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> item </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> iterable </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> condition&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>if</code>以降は必須ではありません。</p>



<p class="wp-block-paragraph">まずは単純な例として、<code>0</code>から<code>9</code>までの数値の2乗した数値を順次リストに加えたい場合を考えます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>squares = &#91;x**2 for x in range(10)&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">squares = &#91;x**</span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> x </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">10</span><span style="color: #D4D4D4">)&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph">コードの読み方は以下の通りです。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><code>for x in range(10)</code>: <code>x</code>に<code>0</code>~<code>9</code>まで順次代入する</li>



<li><code>x**2</code>: xに代入された数値の二乗した数値をリストに加える</li>
</ul>
</div></div>



<p class="wp-block-paragraph"><code>squares</code>の内容は以下となります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>&#91;0, 1, 4, 9, 16, 25, 36, 49, 64, 81&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">&#91;</span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">4</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">9</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">16</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">25</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">36</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">49</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">64</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">81</span><span style="color: #D4D4D4">&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph">続いて、if文を加えた例を考えてみましょう。</p>



<p class="wp-block-paragraph"><code>0</code>から<code>9</code>までの数値の中から<strong>「偶数だけ」を取り出し</strong>、その値に2乗してリストに加えたい場合は以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>squares = &#91;x**2 for x in range(10) if x % 2 == 0&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">squares = &#91;x**</span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> x </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">10</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> x % </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> == </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph">読み方は以下の通りです。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><code>for x in range(10)</code>: <code>0</code>から<code>9</code>までが順に<code>x</code>に入る</li>



<li><code>if x % 2 == 0</code>: <code>x</code>の値が<code>2</code>で割り切れれば次に進む</li>



<li><code>x**2</code>: <code>x</code>を二乗してリストの要素に加える</li>
</ul>
</div></div>



<p class="wp-block-paragraph">初見だとちょっと読むのが大変ですが、このような複雑なロジックをワンライナーで書けるのは大きな魅力です。</p>



<p class="wp-block-paragraph">複数条件を持つ内包表記の場合は、<code>if</code>節内に<code>and</code>や<code>or</code>などを加えます。</p>



<p class="wp-block-paragraph">イメージが湧きやすいように、具体例を挙げて解説します。</p>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset5 animation-fade rtoc_open default" data-id="5252" data-theme="SWELL CHILD">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-1"><code>and</code>を使った具体例</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-2">orを使った例</a></li><li class="rtoc-item"><a href="#rtoc-3">特定の条件を満たす要素のみを含む辞書を作成</a></li><li class="rtoc-item"><a href="#rtoc-4">例2: 文字列内の特定の文字をカウントして辞書を作成</a></li><li class="rtoc-item"><a href="#rtoc-5">単純なロジックに限定して使用</a></li><li class="rtoc-item"><a href="#rtoc-6">可読性を重視する</a></li></ul></li></ol></div><h3 id="rtoc-1"  class="wp-block-heading"><code>and</code>を使った具体例</h3>



<p class="wp-block-paragraph"><code>0</code>から<code>99</code>までの数字のうち、<code>3</code>で割り切れ、かつ（<code>and</code>）<code>5</code>より大きい数の二乗をリストとして生成したい場合は以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>result = &#91;x**2 for x in range(100) if x % 3 == 0 and x > 5&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">result = &#91;x**</span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> x </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">100</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> x % </span><span style="color: #B5CEA8">3</span><span style="color: #D4D4D4"> == </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">and</span><span style="color: #D4D4D4"> x &gt; </span><span style="color: #B5CEA8">5</span><span style="color: #D4D4D4">&#93;</span></span></code></pre></div>



<h3 id="rtoc-2"  class="wp-block-heading">orを使った例</h3>



<p class="wp-block-paragraph"><code>0</code>から<code>99</code>までの数で、<code>2</code>で割り切れるか、または（<code>or</code>）<code>9</code>で割り切れる数をリストに入れる場合は以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>result = &#91;x for x in range(100) if x % 2 == 0 or x % 9 == 0&#93;</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">result = &#91;x </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> x </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">100</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> x % </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> == </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">or</span><span style="color: #D4D4D4"> x % </span><span style="color: #B5CEA8">9</span><span style="color: #D4D4D4"> == </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">&#93;</span></span></code></pre></div>



<p class="wp-block-paragraph">リスト内包表記の辞書版が「辞書内包表記」です。</p>



<p class="wp-block-paragraph">特定のキーとバリューを持つ新たな辞書を作成する方法になります。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>辞書内包表記の基本的な書き方</li>



<li>条件を加えた辞書内包表記</li>
</ul>
</div></div>



<p class="wp-block-paragraph">順番にレベルアップしていきますので、順に解説していきます。</p>



<p class="wp-block-paragraph">リストと同様、辞書にも内包表記があります。</p>



<p class="wp-block-paragraph">基本的な書き方は以下の通り。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>new_dict = {key_expression: value_expression for item in iterable if condition}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">new_dict = {key_expression: value_expression </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> item </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> iterable </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> condition}</span></span></code></pre></div>



<p class="wp-block-paragraph">例として、ある文字列に含まれる各文字の出現回数を数えるものを示します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>text = "hello"
char_count = {char: text.count(char) for char in text}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;hello&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">char_count = {char: text.count(char) </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> char </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> text}</span></span></code></pre></div>



<p class="wp-block-paragraph">読み方としては、以下のようになります。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><code>for char in text</code>: 文字列 “hello” を1文字ずつ<code>char</code>に代入</li>



<li><code>char: text.count(char)</code>: それぞれの文字 <code>char</code> をキーとして、その文字が文字列 “hello” に出現する回数をバリューとする辞書を作成</li>
</ul>
</div></div>



<p class="wp-block-paragraph">実行すると、以下のような出力結果が得られます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>{'h': 1, 'e': 1, 'l': 2, 'o': 1}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">{</span><span style="color: #DCDCAA">&apos;h&apos;</span><span style="color: #DCDCAA">:</span><span style="color: #D4D4D4"> </span><span style="color: #B5CEA8">1</span><span style="color: #CE9178">,</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">&apos;e&apos;:</span><span style="color: #D4D4D4"> </span><span style="color: #B5CEA8">1</span><span style="color: #CE9178">,</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">&apos;l&apos;:</span><span style="color: #D4D4D4"> </span><span style="color: #B5CEA8">2</span><span style="color: #CE9178">,</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">&apos;o&apos;:</span><span style="color: #D4D4D4"> </span><span style="color: #B5CEA8">1</span><span style="color: #CE9178">}</span></span></code></pre></div>



<p class="wp-block-paragraph">先ほどの例では<code>if</code>節なしのシンプルなものでしたので、ここでは条件をつけた内包表記の書き方をご紹介します。</p>



<h3 id="rtoc-3"  class="wp-block-heading">特定の条件を満たす要素のみを含む辞書を作成</h3>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 0から9までの数字の中で、奇数のみをキーとし、その平方を値とする辞書を作成
odd_squares = {x: x**2 for x in range(10) if x % 2 != 0}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># 0から9までの数字の中で、奇数のみをキーとし、その平方を値とする辞書を作成</span></span>
<span class="line"><span style="color: #D4D4D4">odd_squares = {x: x**</span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> x </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">10</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> x % </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4"> != </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">}</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>0</code>から<code>9</code>の中で「奇数のみの値」をキー、「それぞれの数値の二乗」をバリューとして辞書に格納します。</p>



<h3 id="rtoc-4"  class="wp-block-heading">例2: 文字列内の特定の文字をカウントして辞書を作成</h3>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>text = "hello world"
# text から母音のみを抽出し、それぞれの出現回数をカウント
vowel_counts = {char: text.count(char) for char in text if char in "aiueo"}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">text = </span><span style="color: #CE9178">&quot;hello world&quot;</span></span>
<span class="line"><span style="color: #6A9955"># text から母音のみを抽出し、それぞれの出現回数をカウント</span></span>
<span class="line"><span style="color: #D4D4D4">vowel_counts = {char: text.count(char) </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> char </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> text </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> char </span><span style="color: #569CD6">in</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">&quot;aiueo&quot;</span><span style="color: #D4D4D4">}</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>text</code>のうち「母音に含まれる文字」をキー、「その出現回数」をバリューとして辞書に格納します。</p>



<p class="wp-block-paragraph">ここでは内包表記について、以下のようなアドバンス的な内容を解説します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>内包表記のパフォーマンスについて</li>



<li>内包表記のベストプラクティスについて</li>
</ul>
</div></div>



<p class="wp-block-paragraph">それぞれ解説していきます。</p>



<p class="wp-block-paragraph">通常、内包表記は<code>for</code>ループより高速です。</p>



<p class="wp-block-paragraph">これは Python の内部最適化によるもので、内包表記のコードは C 言語レベルで直接実行されるために関数呼び出しのオーバーヘッドが減ります。</p>



<p class="wp-block-paragraph">特にリストや辞書の生成では、内包表記を使うと明らかにパフォーマンスが上がる。</p>



<p class="wp-block-paragraph">ただし、複雑な内包表記はコードが非常に読みづらくなってしまうので、いくらパフォーマンスが上がったとしても可読性を重視して<code>for</code>ループで書くべきシーンは多くあります。</p>



<p class="wp-block-paragraph">内包表記を上手に使うため、以下の点に注意していきましょう。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>単純なロジックに限定して使用</li>



<li>可読性を重視する</li>
</ul>
</div></div>



<p class="wp-block-paragraph">一つずつ、解説していきます。</p>



<h3 id="rtoc-5"  class="wp-block-heading">単純なロジックに限定して使用</h3>



<p class="wp-block-paragraph">内包表記は「単一のループ」と「簡単な条件」に向いた表記方法です。</p>



<p class="wp-block-paragraph">ネストされたループや複雑な条件式を含む場合には、通常の<code>for</code>ループの方が断然読みやすいくなります。</p>



<p class="wp-block-paragraph">無理して内包表記とするのではなく、保守性を考えて<code>for</code>ループを使うべきこともあると理解しておきましょう。</p>



<h3 id="rtoc-6"  class="wp-block-heading">可読性を重視する</h3>



<p class="wp-block-paragraph">内包表記を覚えると、なんでもかんでも内包表記を使いたくなるものです。</p>



<p class="wp-block-paragraph">ところが、先にも触れたように複雑なロジックを内包表記に落とし込もうとすると可読性が著しく損なわれます。</p>



<p class="wp-block-paragraph">そのような場合にはそもそもfor文を使ってコードを組むか、コメントを加えることで後から読んでも意味がわかるように配慮しておくことが重要です。</p>



<p class="wp-block-paragraph">以上の内容をご理解いただければ、内包表記の基礎はバッチリだと思います。</p>



<p class="wp-block-paragraph">初見ではとっつきにくいかと思いますが、少しずつ手を動かして書いていけば必ず「書ける」「読める」ようになります。</p>



<p class="wp-block-paragraph">ぜひ、めげずにトライしてみてくださいね。</p>



<p class="wp-block-paragraph">当ブログでは他にも Python 関連の記事をアップしていますので、よろしければ合わせてご覧になってみてください！</p>



<p class="wp-block-paragraph"><a href="https://cfxlog.com/category/python/">» 参考：CFXLOG – Python に関する記事一覧</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Python】インポートの方法徹底解説！【import, from】</title>
		<link>https://cfxlog.com/python-import/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Thu, 13 Aug 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5251</guid>

					<description><![CDATA[Python ではインポートを行うことで、機能拡張ができます。 本記事ではインポートに必要な知識を網羅的に解説します。 目次 標準ライブラリとサードパーティライブラリ 標準ライブラリのインポート サードパーティライブラリ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-group is-style-crease"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>ライブラリのインポート方法が知りたい！</li>
</ul>
</div></div>



<p class="wp-block-paragraph">Python ではインポートを行うことで、機能拡張ができます。</p>



<p class="wp-block-paragraph">本記事ではインポートに必要な知識を網羅的に解説します。</p>




<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset5 animation-fade rtoc_open default" data-id="5251" data-theme="SWELL CHILD">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji mokuji_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">標準ライブラリとサードパーティライブラリ</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-2">標準ライブラリのインポート</a></li><li class="rtoc-item"><a href="#rtoc-3">サードパーティライブラリのインポート</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4">複数モジュールのインポート方法</a></li><li class="rtoc-item"><a href="#rtoc-5">モジュールの一部だけをインポートする（from）</a></li><li class="rtoc-item"><a href="#rtoc-6">ライブラリに別名をつける（as）</a></li><li class="rtoc-item"><a href="#rtoc-7">if __name__ == &#8220;__main__&#8221; の意味</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-8">module1.py が直接実行された場合</a></li><li class="rtoc-item"><a href="#rtoc-9">他のモジュールから呼び出された場合</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-10">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">標準ライブラリとサードパーティライブラリ</h2>


<p class="wp-block-paragraph">インポートの方法には２つのパターンがあります。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>標準ライブラリのインポート</li>

<li>サードパーティライブラリのインポート</li>
</ul>
</div></div>



<p class="wp-block-paragraph">手順がやや異なるので、一つずつ解説します。</p>



<h3 id="rtoc-2"  class="wp-block-heading">標準ライブラリのインポート</h3>



<p class="wp-block-paragraph">Python に標準でついてくるライブラリのインポートは、コードの先頭で以下のように書きます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import os

# 新しいディレクトリを作成する
new_dir = "path/to/newdir"
os.mkdir(new_dir)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> os</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># 新しいディレクトリを作成する</span></span>
<span class="line"><span style="color:#D4D4D4">new_dir = </span><span style="color:#CE9178">"path/to/newdir"</span></span>
<span class="line"><span style="color:#D4D4D4">os.mkdir(new_dir)</span></span></code></pre></div>



<p class="wp-block-paragraph">5行目の<code>os.mkdir()</code>は<code>os</code>モジュールの機能を利用しているので、1行目のインポート文を書かないとエラーになります。</p>



<h3 id="rtoc-3"  class="wp-block-heading">サードパーティライブラリのインポート</h3>



<p class="wp-block-paragraph">Python に標準搭載されていないライブラリを「サードパーティライブラリ」と呼びます。</p>



<p class="wp-block-paragraph">この場合は、まずライブラリをインストールする必要があります。</p>



<p class="wp-block-paragraph">以下のコマンドをターミナルなどのコンソール上から実行すると、ライブラリがインストールされるはずです。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install requests</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#CE9178"> requests</span></span></code></pre></div>



<p class="wp-block-paragraph">その後にモジュール内でインポートを行いましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import requests

# URLを指定
url = "https://www.example.com/"

# GETリクエストを送信
response = requests.get(url)

# HTTPレスポンスコードを出力
print("Status Code:", response.status_code)

# レスポンスボディをテキストとして出力
print("Response Body:", response.text)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> requests</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># URLを指定</span></span>
<span class="line"><span style="color:#D4D4D4">url = </span><span style="color:#CE9178">"https://www.example.com/"</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># GETリクエストを送信</span></span>
<span class="line"><span style="color:#D4D4D4">response = requests.get(url)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># HTTPレスポンスコードを出力</span></span>
<span class="line"><span style="color:#DCDCAA">print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"Status Code:"</span><span style="color:#D4D4D4">, response.status_code)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># レスポンスボディをテキストとして出力</span></span>
<span class="line"><span style="color:#DCDCAA">print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"Response Body:"</span><span style="color:#D4D4D4">, response.text)</span></span></code></pre></div>



<p class="wp-block-paragraph">最初から入っていないライブラリは、インストールが必要と覚えておきましょう。</p>




<h2 id="rtoc-4"  class="wp-block-heading">複数モジュールのインポート方法</h2>


<p class="wp-block-paragraph">PEP8 というルールによれば、複数モジュールをインポートする場合には１行ずつ分けて書くことになっています。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 良い例
import glob
import os</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#6A9955"># 良い例</span></span>
<span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> glob</span></span>
<span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> os</span></span></code></pre></div>



<p class="wp-block-paragraph">以下はエラーにはならないが、非推奨です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 悪い例
import glob, os</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#6A9955"># 悪い例</span></span>
<span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> glob, os</span></span></code></pre></div>



<p class="wp-block-paragraph">モジュールのインポートは改行でグループ分けしてインポートするのが通例です。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>標準ライブラリ</li>

<li>サードパーティライブラリ</li>

<li>自作ライブラリ</li>
</ul>
</div></div>



<p class="wp-block-paragraph">例えば以下のような感じになります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import glob
import os

import requests

import library1
import library2</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> glob</span></span>
<span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> os</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> requests</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> library1</span></span>
<span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> library2</span></span></code></pre></div>



<p class="wp-block-paragraph">より読みやすいように、ライブラリ名の頭文字を基準としてアルファベット順に並べることもあります。</p>



<p class="wp-block-paragraph">ただしアルファベット順に並べるのはかなり大変なので、<code>isort</code>というフォーマッたを使って自動整形させることが多いです。</p>




<h2 id="rtoc-5"  class="wp-block-heading">モジュールの一部だけをインポートする（from）</h2>


<p class="wp-block-paragraph">以下のように書くことで、モジュールの一部のみをインポートできます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from os import mkdir

# 新しいディレクトリを作成する
new_dir = "path/to/newdir"
mkdir(new_dir)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> os </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> mkdir</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># 新しいディレクトリを作成する</span></span>
<span class="line"><span style="color:#D4D4D4">new_dir = </span><span style="color:#CE9178">"path/to/newdir"</span></span>
<span class="line"><span style="color:#D4D4D4">mkdir(new_dir)</span></span></code></pre></div>



<p class="wp-block-paragraph">複数の関数をインポートするには、カンマ区切りにします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from os import mkdir, path

# 新しいディレクトリを作成する
base_dir = "path/to/newdir"
new_dir = path.join(base_dir, "joindir")
mkdir(new_dir)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> os </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> mkdir, path</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># 新しいディレクトリを作成する</span></span>
<span class="line"><span style="color:#D4D4D4">base_dir = </span><span style="color:#CE9178">"path/to/newdir"</span></span>
<span class="line"><span style="color:#D4D4D4">new_dir = path.join(base_dir, </span><span style="color:#CE9178">"joindir"</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#D4D4D4">mkdir(new_dir)</span></span></code></pre></div>




<h2 id="rtoc-6"  class="wp-block-heading">ライブラリに別名をつける（as）</h2>


<p class="wp-block-paragraph">ライブラリ名が長い場合などには、別名をつけると呼び出しが簡単です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import pandas as pd

# DataFrame を新規作成
df = pd.DataFrame()</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> pandas </span><span style="color:#C586C0">as</span><span style="color:#D4D4D4"> pd</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># DataFrame を新規作成</span></span>
<span class="line"><span style="color:#D4D4D4">df = pd.DataFrame()</span></span></code></pre></div>



<p class="wp-block-paragraph">ただしこの場合には別名での呼び出ししかできず、pandas としてもエラーになります。</p>




<h2 id="rtoc-7"  class="wp-block-heading">if __name__ == &#8220;__main__&#8221; の意味</h2>


<p class="wp-block-paragraph">モジュールの最後の方に、以下のコードが書かれている場合があります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>if __name__ == "__main__":
    print("本モジュールが実行されました。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">if</span><span style="color:#9CDCFE"> __name__</span><span style="color:#D4D4D4"> == </span><span style="color:#CE9178">"__main__"</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"本モジュールが実行されました。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">上記のモジュールを「直接」を実行した場合だけ、<code>if</code>節内が実行されます。</p>



<p class="wp-block-paragraph">地味に重要なのが、<code>__name__</code>はプロパティであり<code>"__main__"</code>は文字列だということです。</p>



<p class="wp-block-paragraph">特定のモジュール名のプロパティとして<code>__name__</code>を実行すると、そのモジュール名が取得できます。</p>



<p class="wp-block-paragraph">つまり、以下の例で<code>print(os.__name__)</code>の実行結果は<code>os</code>となります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import os

# 実行結果は "os" となる
print(os.__name__)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> os</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># 実行結果は "os" となる</span></span>
<span class="line"><span style="color:#DCDCAA">print</span><span style="color:#D4D4D4">(os.</span><span style="color:#9CDCFE">__name__</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">一方で、以下のような<code>print()</code>関数だけが存在するコードを考えてみましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>print(__name__)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">print</span><span style="color:#D4D4D4">(</span><span style="color:#9CDCFE">__name__</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">ファイル名を<code>module1.py</code>とします。</p>



<p class="wp-block-paragraph">実は、<code>__name__</code>の内容は状況によって結果が異なります。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>module1.pyが直接実行された場合</li>

<li>他のモジュールから呼び出された場合</li>
</ul>
</div></div>



<p class="wp-block-paragraph">それぞれ説明します。</p>



<h3 id="rtoc-8"  class="wp-block-heading">module1.py が直接実行された場合</h3>



<p class="wp-block-paragraph">module1.py は、以下のような<code>print()</code>関数だけが書かれたものでした。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>print(__name__)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">print</span><span style="color:#D4D4D4">(</span><span style="color:#9CDCFE">__name__</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">以下のように、module1.pyが直接実行されたとします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>python module1.py</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">python</span><span style="color:#CE9178"> module1.py</span></span></code></pre></div>



<p class="wp-block-paragraph">すると、<code>print(__name__)</code>の実行結果は<code>"__main__"</code>になります。</p>



<p class="is-style-icon_announce wp-block-paragraph">本来はモジュール名が出力されますが、直接実行されたモジュール内の<code>__name__</code>は特別に<code>__main__</code>という文字列が格納されます。</p>



<h3 id="rtoc-9"  class="wp-block-heading">他のモジュールから呼び出された場合</h3>



<p class="wp-block-paragraph">例えば、以下のようなmodule2.pyがあったとします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import module1</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> module1</span></span></code></pre></div>



<p class="wp-block-paragraph">そして、先ほどとは異なり以下のコマンドを実行したとします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>python module2.py</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">python</span><span style="color:#CE9178"> module2.py</span></span></code></pre></div>



<p class="wp-block-paragraph">すると、module2.pyが実行されることで、import 文を通して間接的にmodule1.pyが実行されることになります。</p>



<p class="wp-block-paragraph">この場合には<code>print(__name__)</code>の実行結果は<code>"module1"</code>となります。</p>



<p class="wp-block-paragraph">そのモジュール自体が実行された場合のみ、<code>__name__</code>は<code>__main__</code>になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>if __name__ == "__main__":
    print("本モジュールが直接実行されました。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">if</span><span style="color:#9CDCFE"> __name__</span><span style="color:#D4D4D4"> == </span><span style="color:#CE9178">"__main__"</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"本モジュールが直接実行されました。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>if</code>節内に書いたコードに以下の役割を持たせられます。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>デバッグ用コード</li>

<li>デモ用コード</li>

<li>テスト用コード</li>
</ul>
</div></div>



<p class="wp-block-paragraph">これらは他のモジュールから呼び出された時には実行されないので、スタンドアロンのスクリプトとしてもモジュールとしても使えます。</p>




<h2 id="rtoc-10"  class="wp-block-heading">まとめ</h2>


<p class="wp-block-paragraph">Python のインポートの基礎をご紹介してきました。</p>



<p class="wp-block-paragraph">本記事でご紹介してきた書き方をマスターいただければ、基本的な書き方としては完璧かと思います。</p>



<p class="wp-block-paragraph">本ブログでは Python 関連の記事も順次アップしておりますので、ぜひ他記事もご覧になってみてください。</p>



<p class="wp-block-paragraph"><a href="https://cfxlog.com/category/python/">» 参考：CFXLOG – Python に関する記事一覧</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Python】if 文の基礎的な書き方を解説</title>
		<link>https://cfxlog.com/python-if/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Wed, 12 Aug 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5243</guid>

					<description><![CDATA[このような疑問にお答えします。 if文はプログラムの条件分岐を制御するもので、forに並んで最重要概念の一つです。 本記事では以下の内容を解説します。 ごく基本的な事項を中心に解説していきます。 まずはif文の基本から解 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-group is-style-crease"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>Python の if 文の書き方が知りたい！</li>

<li>ワンライナーで書くにはどうやったらいい？</li>
</ul>
</div></div>



<p class="wp-block-paragraph">このような疑問にお答えします。</p>



<p class="wp-block-paragraph"><code>if</code>文はプログラムの条件分岐を制御するもので、<code>for</code>に並んで最重要概念の一つです。</p>



<p class="wp-block-paragraph">本記事では以下の内容を解説します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>if 文の基本的な書き方</li>

<li>if 文の応用的な使い方</li>
</ul>
</div></div>



<p class="wp-block-paragraph">ごく基本的な事項を中心に解説していきます。</p>



<p class="wp-block-paragraph">まずは<code>if</code>文の基本から解説します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>if のみを使った書き方</li>

<li>if と else を使った書き方</li>

<li>if, elif, else を使った方法</li>
</ul>
</div></div>



<p class="wp-block-paragraph">それぞれ解説していきます。</p>




<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset5 animation-fade rtoc_open default" data-id="5243" data-theme="SWELL CHILD">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji mokuji_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">if文の基本的な書き方</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-2">ifとelseを使った書き方</a></li><li class="rtoc-item"><a href="#rtoc-3">if, elif, elseを使った書き方</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4">if文の応用的な使い方</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-5">andとorを使った複合条件</a></li><li class="rtoc-item"><a href="#rtoc-6">三項演算子でif文を1行にする</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-7">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">if文の基本的な書き方</h2>


<p class="wp-block-paragraph">ある条件に合致した場合のみ処理を行うには、以下のように<code>if</code>節を書きます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>number = 5

if number == 5:
    print("number は 5 です。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">number = </span><span style="color:#B5CEA8">5</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">5</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 5 です。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>if</code>の後に「条件式」と「コロン（<code>:</code>）」を続けて、条件に合致した場合の処理はインデントを開けて書きます。</p>




<h3 id="rtoc-2"  class="wp-block-heading">ifとelseを使った書き方</h3>


<p class="wp-block-paragraph">「条件に合致した場合」と「条件に合致しなかった場合」の処理を指定するには、<code>if</code>と<code>else</code>を併用します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>number = 5

if number == 5:
    print("number は 5 です。")
else:
    print("number は 5 以外です。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">number = </span><span style="color:#B5CEA8">5</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">5</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 5 です。"</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">else</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 5 以外です。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>




<h3 id="rtoc-3"  class="wp-block-heading">if, elif, elseを使った書き方</h3>


<p class="wp-block-paragraph"><code>if</code>に続けてさらに別の条件を続ける場合には、<code>elif</code>を使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>number = 5

if number == 5:
    print("number は 5 です。")
elif number == 6:
    print("number は 6 です。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">number = </span><span style="color:#B5CEA8">5</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">5</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 5 です。"</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">elif</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">6</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 6 です。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">上記の例ではまず<code>number</code>が<code>5</code>かどうかを判定し、続いて<code>number</code>が<code>6</code>であるか判定しています。</p>



<p class="wp-block-paragraph">もし条件をさらに追加したい場合には、<code>elif</code>を増やします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>number = 5

if number == 5:
    print("number は 5 です。")
elif number == 6:
    print("number は 6 です。")
elif number == 7:
    print("number は 7 です。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">number = </span><span style="color:#B5CEA8">5</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">5</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 5 です。"</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">elif</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">6</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 6 です。"</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">elif</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">7</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 7 です。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">最後にどのif, elifにも当てはまらない場合の条件分岐を付け加えたい場合には、最後にelseを書きます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>number = 5

if number == 5:
    print("number は 5 です。")
elif number == 6:
    print("number は 6 です。")
elif number == 7:
    print("number は 7 です。")
else:
    print("number は 5, 6, 7 以外です。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">number = </span><span style="color:#B5CEA8">5</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">5</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 5 です。"</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">elif</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">6</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 6 です。"</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">elif</span><span style="color:#D4D4D4"> number == </span><span style="color:#B5CEA8">7</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 7 です。"</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">else</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 5, 6, 7 以外です。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>




<h2 id="rtoc-4"  class="wp-block-heading">if文の応用的な使い方</h2>


<p class="wp-block-paragraph">if文ではTrueの場合にインデント内が実行されます。</p>



<p class="wp-block-paragraph">そうすると、条件式に真偽に関する式を入れることで条件分岐させることができます。</p>



<p class="wp-block-paragraph">例えば次の通り。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>is_ok = "OK"

if is_ok == "OK":
   print("OK でした")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">is_ok = </span><span style="color:#CE9178">"OK"</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> is_ok == </span><span style="color:#CE9178">"OK"</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">   print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"OK でした"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">これを応用して、以下のような演算子を使って条件分岐させることもできます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>number = 5

if number &gt;= 5:
   print("number は 5 以上の値です。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">number = </span><span style="color:#B5CEA8">5</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> number >= </span><span style="color:#B5CEA8">5</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">   print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"number は 5 以上の値です。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">演算子には、例えば以下のようなものが使えます。</p>



<figure class="wp-block-table"><table><thead><tr><th>演算子</th><th>意味</th></tr></thead><tbody><tr><td>a == b</td><td>aとbが等しい</td></tr><tr><td>a != b</td><td>aとbが等しくない</td></tr><tr><td>a &lt; b</td><td>aはbより小さい</td></tr><tr><td>a &gt; b</td><td>aはbより大きい</td></tr><tr><td>a &lt;= b</td><td>aはb以下</td></tr><tr><td>a &gt;= b</td><td>aはb以上</td></tr><tr><td>a is b</td><td>aとbは同じオブジェクト</td></tr><tr><td>a is not b</td><td>aとbは異なるオブジェクト</td></tr></tbody></table><figcaption class="wp-element-caption">演算子とその意味</figcaption></figure>



<p class="wp-block-paragraph">より Pythonic な書き方として、以下のようなものがあります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>is_ok = True

if is_ok:
   print("OK です！")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">is_ok = </span><span style="color:#569CD6">True</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> is_ok:</span></span>
<span class="line"><span style="color:#DCDCAA">   print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"OK です！"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">条件式が<code>True</code>なら<code>if</code>節が実行されます。</p>



<p class="wp-block-paragraph">反対に、<code>False</code>の場合に実行したい場合には以下のようにします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>is_ok = False

if not is_ok:
   print("NG です！")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">is_ok = </span><span style="color:#569CD6">False</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#569CD6"> not</span><span style="color:#D4D4D4"> is_ok:</span></span>
<span class="line"><span style="color:#DCDCAA">   print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"NG です！"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>if</code>の後に<code>not</code>を書くことで、否定を表すことを利用しました。</p>



<p class="wp-block-paragraph">あるリストに特定の要素を含むかどうか判定するには<code>in</code>を使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>num_list = [1, 2, 3, 4, 5]

if 1 in num_list:
   print("1 を含みます。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">num_list = [</span><span style="color:#B5CEA8">1</span><span style="color:#D4D4D4">, </span><span style="color:#B5CEA8">2</span><span style="color:#D4D4D4">, </span><span style="color:#B5CEA8">3</span><span style="color:#D4D4D4">, </span><span style="color:#B5CEA8">4</span><span style="color:#D4D4D4">, </span><span style="color:#B5CEA8">5</span><span style="color:#D4D4D4">]</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#B5CEA8"> 1</span><span style="color:#569CD6"> in</span><span style="color:#D4D4D4"> num_list:</span></span>
<span class="line"><span style="color:#DCDCAA">   print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"1 を含みます。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">もちろん、<code>not</code>を使うことで「含まない」ことも表現できます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>num_list = [1, 2, 3, 4, 5]

if 1 not in num_list:
   print("1 を含みません。")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">num_list = [</span><span style="color:#B5CEA8">1</span><span style="color:#D4D4D4">, </span><span style="color:#B5CEA8">2</span><span style="color:#D4D4D4">, </span><span style="color:#B5CEA8">3</span><span style="color:#D4D4D4">, </span><span style="color:#B5CEA8">4</span><span style="color:#D4D4D4">, </span><span style="color:#B5CEA8">5</span><span style="color:#D4D4D4">]</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#B5CEA8"> 1</span><span style="color:#569CD6"> not</span><span style="color:#569CD6"> in</span><span style="color:#D4D4D4"> num_list:</span></span>
<span class="line"><span style="color:#DCDCAA">   print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"1 を含みません。"</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">実務でよく使うテクニックなので、覚えておきましょう。</p>




<h3 id="rtoc-5"  class="wp-block-heading">andとorを使った複合条件</h3>


<p class="wp-block-paragraph"><code>and</code>や<code>or</code>を使うことで、より複雑な条件を加えることが可能です。</p>



<p class="wp-block-paragraph">例えば、次のような形です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>age = 25
has_license = True

if age &gt;= 18 and has_license:
    print("You can drive.")
else:
    print("You cannot drive.")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">age = </span><span style="color:#B5CEA8">25</span></span>
<span class="line"><span style="color:#D4D4D4">has_license = </span><span style="color:#569CD6">True</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> age >= </span><span style="color:#B5CEA8">18</span><span style="color:#569CD6"> and</span><span style="color:#D4D4D4"> has_license:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"You can drive."</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">else</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"You cannot drive."</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>a and b</code>とした場合には、<code>a</code>も<code>b</code>も<code>True</code>の場合に<code>if</code>節内が実行されます。</p>



<p class="wp-block-paragraph">今回の場合では<code>age</code>が<code>25</code>なので<code>True</code>、<code>has_license</code>も<code>True</code>なので、<code>if</code>節内が実行されます。</p>



<p class="wp-block-paragraph">また、<code>or</code>を使った例もご紹介します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>temperature = 30
is_raining = False

if temperature &gt; 25 or is_raining:
    print("Let's use the air conditioner.")
else:
    print("We don't need air conditioning.")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">temperature = </span><span style="color:#B5CEA8">30</span></span>
<span class="line"><span style="color:#D4D4D4">is_raining = </span><span style="color:#569CD6">False</span></span>
<span class="line"></span>
<span class="line"><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> temperature > </span><span style="color:#B5CEA8">25</span><span style="color:#569CD6"> or</span><span style="color:#D4D4D4"> is_raining:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"Let's use the air conditioner."</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#C586C0">else</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#DCDCAA">    print</span><span style="color:#D4D4D4">(</span><span style="color:#CE9178">"We don't need air conditioning."</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>a or b</code>とすると、<code>a</code>と<code>b</code>のいずれか、またはどちらも<code>True</code>の場合に<code>if</code>節内が実行されます。</p>



<p class="wp-block-paragraph">上記の例では、「気温が25度を超えている」か「雨が降っている」のどちらか一方でも<code>True</code>なら<code>if</code>節内が実行されます。</p>



<p class="wp-block-paragraph">今回は気温が25度以上なので、雨が降っていなくても<code>if</code>節内が実行されることになります。</p>




<h3 id="rtoc-6"  class="wp-block-heading">三項演算子でif文を1行にする</h3>


<p class="wp-block-paragraph">三項演算子を使えば<code>if</code>文を一行で表現できます。</p>



<p class="wp-block-paragraph">書き方は以下の通りです。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>"True の場合の値" if 条件式 else "False の場合の値"</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#CE9178">"True の場合の値"</span><span style="color:#C586C0"> if</span><span style="color:#D4D4D4"> 条件式 </span><span style="color:#C586C0">else</span><span style="color:#CE9178"> "False の場合の値"</span></span></code></pre></div>



<p class="wp-block-paragraph">これではちょっと分かりづらいと思うので、実際のコード例で確認しましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 比較対象の数字を定義
a = 10
b = 20

# 三項演算子で大きい方を取得
max_value = a if a &gt; b else b
print(max_value)  # 20が出力される</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#6A9955"># 比較対象の数字を定義</span></span>
<span class="line"><span style="color:#D4D4D4">a = </span><span style="color:#B5CEA8">10</span></span>
<span class="line"><span style="color:#D4D4D4">b = </span><span style="color:#B5CEA8">20</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># 三項演算子で大きい方を取得</span></span>
<span class="line"><span style="color:#D4D4D4">max_value = a </span><span style="color:#C586C0">if</span><span style="color:#D4D4D4"> a > b </span><span style="color:#C586C0">else</span><span style="color:#D4D4D4"> b</span></span>
<span class="line"><span style="color:#DCDCAA">print</span><span style="color:#D4D4D4">(max_value)  </span><span style="color:#6A9955"># 20が出力される</span></span></code></pre></div>



<p class="wp-block-paragraph">上記の場合には単純に「大きい方の数字」を出力していますが、以下のように文字列を出力することもできます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 比較対象の数字を定義
a = 10
b = 20

# 三項演算子で大きい方を取得
which_value = "10が選択されました" if a &gt; b else "20が選択されました"
print(which_value)  # "20が選択されました" が出力される</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#6A9955"># 比較対象の数字を定義</span></span>
<span class="line"><span style="color:#D4D4D4">a = </span><span style="color:#B5CEA8">10</span></span>
<span class="line"><span style="color:#D4D4D4">b = </span><span style="color:#B5CEA8">20</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># 三項演算子で大きい方を取得</span></span>
<span class="line"><span style="color:#D4D4D4">which_value = </span><span style="color:#CE9178">"10が選択されました"</span><span style="color:#C586C0"> if</span><span style="color:#D4D4D4"> a > b </span><span style="color:#C586C0">else</span><span style="color:#CE9178"> "20が選択されました"</span></span>
<span class="line"><span style="color:#DCDCAA">print</span><span style="color:#D4D4D4">(which_value)  </span><span style="color:#6A9955"># "20が選択されました" が出力される</span></span></code></pre></div>



<p class="wp-block-paragraph">三項演算子の戻り値として「値」の代わりに「式そのもの」を指定できます。</p>



<p class="wp-block-paragraph">日本語で表現すると、以下のようになります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>"True の場合の式" if 条件式 else "False の場合の式"</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#CE9178">"True の場合の式"</span><span style="color:#C586C0"> if</span><span style="color:#D4D4D4"> 条件式 </span><span style="color:#C586C0">else</span><span style="color:#CE9178"> "False の場合の式"</span></span></code></pre></div>



<p class="wp-block-paragraph">このようにすることで、条件式の結果次第で計算式を変えることができます。</p>



<p class="wp-block-paragraph">以下の例では、大きい方の数字を二倍した値が取得されます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 比較対象の数字を定義
a = 10
b = 20

# 三項演算子で大きい方を取得
max_value_double = a * 2 if a &gt; b else b * 2
print(max_value_double)  # 40が出力される</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#6A9955"># 比較対象の数字を定義</span></span>
<span class="line"><span style="color:#D4D4D4">a = </span><span style="color:#B5CEA8">10</span></span>
<span class="line"><span style="color:#D4D4D4">b = </span><span style="color:#B5CEA8">20</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># 三項演算子で大きい方を取得</span></span>
<span class="line"><span style="color:#D4D4D4">max_value_double = a * </span><span style="color:#B5CEA8">2</span><span style="color:#C586C0"> if</span><span style="color:#D4D4D4"> a > b </span><span style="color:#C586C0">else</span><span style="color:#D4D4D4"> b * </span><span style="color:#B5CEA8">2</span></span>
<span class="line"><span style="color:#DCDCAA">print</span><span style="color:#D4D4D4">(max_value_double)  </span><span style="color:#6A9955"># 40が出力される</span></span></code></pre></div>




<h2 id="rtoc-7"  class="wp-block-heading">まとめ</h2>


<p class="wp-block-paragraph"><code>if</code>文は Python を学習する上で最重要概念です。</p>



<p class="wp-block-paragraph">今回の基本的な事項をマスターして、Python をストレスなく書けるようにしていきましょう！</p>



<p class="wp-block-paragraph">ご不明点がありましたら、下のコメント欄よりお気軽にどうぞ。</p>



<p class="wp-block-paragraph">また、本ブログの Python 関連記事もぜひ覗いてみてください。</p>



<p class="wp-block-paragraph"><a href="https://cfxlog.com/category/python/">» 参考：CFXLOG – Python に関する記事一覧</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Python】for ループの基礎を徹底解説！</title>
		<link>https://cfxlog.com/python-forloop/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Tue, 11 Aug 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5242</guid>

					<description><![CDATA[<p><img src="https://cfxlog.com/wp-content/uploads/2026/08/python-forloop.jpg" class="webfeedsFeaturedVisual" /></p>このような悩みにお答えします。 Python のループ処理で最もメジャーなものがfor文です。 基本的にはループ処理のほとんどがforで書けるので、特別な理由がなければfor文を使うことが多いと思います。 ごく基本的な文 [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img src="https://cfxlog.com/wp-content/uploads/2026/08/python-forloop.jpg" class="webfeedsFeaturedVisual" /></p>
<div class="wp-block-group is-style-crease"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>Python の for ループ処理がよくわからない…</li>
</ul>
</div></div>



<p class="wp-block-paragraph">このような悩みにお答えします。</p>



<p class="wp-block-paragraph">Python のループ処理で最もメジャーなものが<code>for</code>文です。</p>



<p class="wp-block-paragraph">基本的にはループ処理のほとんどが<code>for</code>で書けるので、特別な理由がなければ<code>for</code>文を使うことが多いと思います。</p>



<p class="wp-block-paragraph">ごく基本的な文法ではあるものの、細かい事項まで見ていくと意外と奥が深いです。</p>



<p class="wp-block-paragraph">本記事を通して、<code>for</code>ループをマスターしていきましょう！</p>



<p class="wp-block-paragraph">Python でもっともよく使われるループ処理が<code>for</code>を使った方法です。</p>



<p class="wp-block-paragraph">ここでは、以下の内容をご説明します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>基本的な<code>for</code>文の書き方</li>



<li>途中でループを抜ける方法</li>



<li>処理をスキップする方法</li>



<li>正常終了後の処理を追加する</li>



<li>インデックスカウンタを回す</li>
</ul>
</div></div>



<p class="wp-block-paragraph">それぞれ、みていきましょう。</p>



<p class="wp-block-paragraph">まずはコード例から<code>for</code>文の書き方を確認しましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>area_list = &#91;"Asia", "Africa", "America", "Europe"&#93;

for area in area_list:
    print(area)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">area_list = &#91;</span><span style="color: #CE9178">&quot;Asia&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;America&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Europe&quot;</span><span style="color: #D4D4D4">&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> area </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> area_list:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(area)</span></span></code></pre></div>



<p class="wp-block-paragraph">上記では<code>area_list</code>が<code>area</code>に順次代入されます。</p>



<p class="wp-block-paragraph">出力結果は以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>Asia
Africa
America
Europe</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">Asia</span></span>
<span class="line"><span style="color: #DCDCAA">Africa</span></span>
<span class="line"><span style="color: #DCDCAA">America</span></span>
<span class="line"><span style="color: #DCDCAA">Europe</span></span></code></pre></div>



<p class="wp-block-paragraph">途中でループを抜けさせる場合には、<code>break</code>を使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>area_list = &#91;"Asia", "Africa", "America", "Europe"&#93;

for area in area_list:
    if area == "Africa":
        break
    print(area)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">area_list = &#91;</span><span style="color: #CE9178">&quot;Asia&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;America&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Europe&quot;</span><span style="color: #D4D4D4">&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> area </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> area_list:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> area == </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">break</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(area)</span></span></code></pre></div>



<p class="wp-block-paragraph">上記の例では、<code>area</code>が<code>Africa</code>になった場合にループを抜けるようになっています。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>Asia</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">Asia</span></span></code></pre></div>



<p class="wp-block-paragraph">つまり、<code>Africa</code>の前のインデックスである<code>Asia</code>だけが<code>print()</code>された後にループを抜けることになります。</p>



<p class="wp-block-paragraph">ある処理だけをスキップする場合には<code>continue</code>を使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>area_list = &#91;"Asia", "Africa", "America", "Europe"&#93;

for area in area_list:
    if area == "Africa":
        continue
    print(area)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">area_list = &#91;</span><span style="color: #CE9178">&quot;Asia&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;America&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Europe&quot;</span><span style="color: #D4D4D4">&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> area </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> area_list:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> area == </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">continue</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(area)</span></span></code></pre></div>



<p class="wp-block-paragraph">つまり、上記の例では<code>Africa</code>だけがスキップ対象となります。</p>



<p class="wp-block-paragraph">出力結果は以下です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>Asia
America
Europe</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">Asia</span></span>
<span class="line"><span style="color: #DCDCAA">America</span></span>
<span class="line"><span style="color: #DCDCAA">Europe</span></span></code></pre></div>



<p class="wp-block-paragraph">ループが正常に終了した時の処理は、<code>else</code>で表現できます。</p>



<p class="wp-block-paragraph">正常終了とは「<code>for</code>ループがリストを消化し切って自然に終了した場合」と言い換えることができます。</p>



<p class="wp-block-paragraph">つまり、<code>break</code>で強制的にループを抜ける場合には<code>else</code>ブロックが実行されません。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>area_list = &#91;"Asia", "Africa", "America", "Europe"&#93;

for area in area_list:
    print(area)
else:
    print("Successfully for loop.")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">area_list = &#91;</span><span style="color: #CE9178">&quot;Asia&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;America&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Europe&quot;</span><span style="color: #D4D4D4">&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> area </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> area_list:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(area)</span></span>
<span class="line"><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;Successfully for loop.&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">実行結果は以下です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>Asia
Africa
America
Europe
Successfully for loop.</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">Asia</span></span>
<span class="line"><span style="color: #DCDCAA">Africa</span></span>
<span class="line"><span style="color: #DCDCAA">America</span></span>
<span class="line"><span style="color: #DCDCAA">Europe</span></span>
<span class="line"><span style="color: #DCDCAA">Successfully</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">for</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">loop.</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>continue</code>が存在する場合も考えてみましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>area_list = &#91;"Asia", "Africa", "America", "Europe"&#93;

for area in area_list:
    if area == "Africa":
        continue
    print(area)
else:
    print("Successfully for loop.")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">area_list = &#91;</span><span style="color: #CE9178">&quot;Asia&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;America&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Europe&quot;</span><span style="color: #D4D4D4">&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> area </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> area_list:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> area == </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">continue</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(area)</span></span>
<span class="line"><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;Successfully for loop.&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>continue</code>では、プログラムは正常に最後まで到達するので<code>else</code>以下が実行されます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>Asia
America
Europe
Successfully for loop.</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">Asia</span></span>
<span class="line"><span style="color: #DCDCAA">America</span></span>
<span class="line"><span style="color: #DCDCAA">Europe</span></span>
<span class="line"><span style="color: #DCDCAA">Successfully</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">for</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">loop.</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>break</code>は正常終了とは見做されず、<code>else</code>以下は実行されません。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>area_list = &#91;"Asia", "Africa", "America", "Europe"&#93;

for area in area_list:
    if area == "Africa":
        break
    print(area)
else:
    print("Successfully for loop.")</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">area_list = &#91;</span><span style="color: #CE9178">&quot;Asia&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;America&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Europe&quot;</span><span style="color: #D4D4D4">&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> area </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> area_list:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> area == </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">break</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(area)</span></span>
<span class="line"><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;Successfully for loop.&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">実行結果に<code>Successfully for loop.</code>の文字列はありません。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>Asia</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">Asia</span></span></code></pre></div>



<p class="wp-block-paragraph">インデックスカウンタを回すには<code>range()</code>関数を使います。</p>



<p class="wp-block-paragraph">最も基本的なインデックスカウンタの回し方は以下です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>for i in range(5):
    print(i)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> i </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">5</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(i)</span></span></code></pre></div>



<p class="wp-block-paragraph">出力結果は以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>0
1
2
3
4</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">0</span></span>
<span class="line"><span style="color: #DCDCAA">1</span></span>
<span class="line"><span style="color: #DCDCAA">2</span></span>
<span class="line"><span style="color: #DCDCAA">3</span></span>
<span class="line"><span style="color: #DCDCAA">4</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>range()</code>関数の第一引数に「開始番号」を、第二引数に「終了番号」を指定できます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>for i in range(1, 5):
    print(i)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> i </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">5</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(i)</span></span></code></pre></div>



<p class="wp-block-paragraph">出力結果は以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>1
2
3
4</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">1</span></span>
<span class="line"><span style="color: #DCDCAA">2</span></span>
<span class="line"><span style="color: #DCDCAA">3</span></span>
<span class="line"><span style="color: #DCDCAA">4</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>range()</code>関数では、終了値は含まれません。</p>



<p class="wp-block-paragraph">そのため、第二引数に<code>5</code>としても<code>4</code>までが表示されることになります。</p>



<p class="wp-block-paragraph"><code>range()</code>関数の第一引数に「開始番号」を、第二引数に「終了番号」を、第三引数に「ステップ間隔」を指定します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>for i in range(1, 5, 2):
    print(i)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> i </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">5</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(i)</span></span></code></pre></div>



<p class="wp-block-paragraph">出力結果は以下となります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>1
3</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">1</span></span>
<span class="line"><span style="color: #DCDCAA">3</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>1</code>から<code>4</code>まで数値を、<code>2</code>ずつ値を増やしていくことになります。</p>



<p class="wp-block-paragraph">enumerate()関数を使うと、リストの要素と同時にインデックスを生成できます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>area_list = &#91;"Asia", "Africa", "America", "Europe"&#93;

for i, area in enumerate(area_list):
    print(i, area)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">area_list = &#91;</span><span style="color: #CE9178">&quot;Asia&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;America&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Europe&quot;</span><span style="color: #D4D4D4">&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> i, area </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">enumerate</span><span style="color: #D4D4D4">(area_list):</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(i, area)</span></span></code></pre></div>



<p class="wp-block-paragraph">以下のように、リストの要素とともにインデックス番号が出力されます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>0 Asia
1 Africa
2 America
3 Europe</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">0</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">Asia</span></span>
<span class="line"><span style="color: #DCDCAA">1</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">Africa</span></span>
<span class="line"><span style="color: #DCDCAA">2</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">America</span></span>
<span class="line"><span style="color: #DCDCAA">3</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">Europe</span></span></code></pre></div>



<p class="wp-block-paragraph">なお、<code>enumerate()</code>関数の第二引数に数値を渡すと始まりの数値が指定できます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>area_list = &#91;"Asia", "Africa", "America", "Europe"&#93;

for i, area in enumerate(area_list, 1):
    print(i, area)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">area_list = &#91;</span><span style="color: #CE9178">&quot;Asia&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Africa&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;America&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;Europe&quot;</span><span style="color: #D4D4D4">&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> i, area </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">enumerate</span><span style="color: #D4D4D4">(area_list, </span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(i, area)</span></span></code></pre></div>



<p class="wp-block-paragraph">上記では1始まりにしたので、出力結果は以下になります。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>1 Asia
2 Africa
3 America
4 Europe</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #DCDCAA">1</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">Asia</span></span>
<span class="line"><span style="color: #DCDCAA">2</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">Africa</span></span>
<span class="line"><span style="color: #DCDCAA">3</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">America</span></span>
<span class="line"><span style="color: #DCDCAA">4</span><span style="color: #D4D4D4"> </span><span style="color: #CE9178">Europe</span></span></code></pre></div>



<p class="wp-block-paragraph">ここまでで<code>for</code>ループの書き方をご紹介してきました。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>for を使った基本的なループ処理の方法</li>



<li>for, range()を使ってインデックスカウンタを回す</li>
</ul>
</div></div>



<p class="wp-block-paragraph">基本的なループ処理は今回ご紹介したもので十分対応可能です。</p>



<p class="wp-block-paragraph">本ブログではPythonに関する記事を順次アップしております。ぜひ、他記事の方もご覧になってみてください。</p>



<p class="wp-block-paragraph"><a href="https://cfxlog.com/category/python/">» 参考：CFXLOG – Python に関する記事一覧</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Python】コメントアウト・コメントの書き方</title>
		<link>https://cfxlog.com/python-comment/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Mon, 10 Aug 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5250</guid>

					<description><![CDATA[<p><img src="https://cfxlog.com/wp-content/uploads/2026/08/python-comment-1024x538.jpg" class="webfeedsFeaturedVisual" /></p>このような疑問にお答えします。 Python は他のプログラミング言語と比べて読みやすい言語ですが、それでも複雑なコードだと視認性は一気に低下します。 そこで便利なのがコメント処理です。 コメント部分は「プログラムの処理 [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img src="https://cfxlog.com/wp-content/uploads/2026/08/python-comment-1024x538.jpg" class="webfeedsFeaturedVisual" /></p>
<div class="wp-block-group is-style-crease"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>Python でコメントを書きたい</li>



<li>コードをコメントアウトしたい</li>
</ul>
</div></div>



<p class="wp-block-paragraph">このような疑問にお答えします。</p>



<p class="wp-block-paragraph">Python は他のプログラミング言語と比べて読みやすい言語ですが、それでも複雑なコードだと視認性は一気に低下します。</p>



<p class="wp-block-paragraph">そこで便利なのがコメント処理です。</p>



<p class="wp-block-paragraph">コメント部分は「プログラムの処理上、何も書いていないこと」と同じ扱いになります。</p>



<p class="wp-block-paragraph">そのため、コードの説明などをコメントとして書き加えればコードの内容を即座に理解できます。</p>



<p class="is-style-bg_stripe wp-block-paragraph"><strong>「プログラムは書く時間よりも読む時間の方が多い。そのため、読みやすさは極めて重要である」</strong></p>



<p class="wp-block-paragraph">読みやすいコードを書くため、Python におけるコメントアウトの方法をマスターしていきましょう。</p>



<p class="wp-block-paragraph">本記事では以下の内容をお伝えします。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><code>#</code>を使ったコメント</li>



<li><code>"""</code>を使ったコメント</li>



<li>関数アノテーションでのコメント</li>



<li>Python の標準スタイルガイドのルール</li>
</ul>
</div></div>



<p class="wp-block-paragraph">それぞれ、解説していきます。</p>



<p class="wp-block-paragraph">最も基本的なコメントが、<code>#</code>を使ったものです。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>インラインコメント</li>



<li>ブロックコメント</li>
</ul>
</div></div>



<p class="wp-block-paragraph">上記について、詳しく解説していきます。</p>



<p class="wp-block-paragraph">１行まるごとコメントにしたい場合は、文頭に<code>#</code>を書きます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># プログラミング言語を入力
code_type = "python"</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># プログラミング言語を入力</span></span>
<span class="line"><span style="color: #D4D4D4">code_type = </span><span style="color: #CE9178">&quot;python&quot;</span></span></code></pre></div>



<p class="wp-block-paragraph">上記の場合には1行目がコメントと解釈され、無視されます。</p>



<p class="wp-block-paragraph">2行目は<code>#</code>がないので、プログラムコードとして実行されます。</p>



<p class="wp-block-paragraph">コードの途中で<code>#</code>を入れることで、<code>#</code>以降がコメントとして解釈されます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>code_type = "python"  # プログラミング言語を入力</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">code_type = </span><span style="color: #CE9178">&quot;python&quot;</span><span style="color: #D4D4D4">  </span><span style="color: #6A9955"># プログラミング言語を入力</span></span></code></pre></div>



<p class="wp-block-paragraph">つまり、<code>code_type = "python"</code>だけが実行されることになります。</p>



<figure class="wp-block-image size-large"><img alt="" data-aspectratio="1024/538" decoding="async" height="538" src="https://cfxlog.com/wp-content/uploads/2026/07/python-comment-3-1024x538-1.jpg" width="1024"/></figure>



<p class="wp-block-paragraph">Python の関数では、クオートを3つ並べてコメントを書き込みます。</p>



<p class="wp-block-paragraph">なお<code>"""</code>は厳密にはコメントではなく、文字列としての扱いです。</p>



<p class="wp-block-paragraph">トリプルクオートで使える文字は<code>"</code>（ダブルクオート）と<code>'</code>（シングルクオート）の二つです。</p>



<p class="wp-block-paragraph">以下のように、コメントをクオート３つ繋げて囲みます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># シングルクオートを使った場合
def single_quate():
    '''
    ここにコメントを書く
    '''
    return None

# ダブルクオートを使った場合
def double_quate():
    """
    ここにコメントを書く
    """
    return None</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># シングルクオートを使った場合</span></span>
<span class="line"><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">single_quate</span><span style="color: #D4D4D4">():</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #CE9178">&apos;&apos;&apos;</span></span>
<span class="line"><span style="color: #CE9178">    ここにコメントを書く</span></span>
<span class="line"><span style="color: #CE9178">    &apos;&apos;&apos;</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">return</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">None</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955"># ダブルクオートを使った場合</span></span>
<span class="line"><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">double_quate</span><span style="color: #D4D4D4">():</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #CE9178">&quot;&quot;&quot;</span></span>
<span class="line"><span style="color: #CE9178">    ここにコメントを書く</span></span>
<span class="line"><span style="color: #CE9178">    &quot;&quot;&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">return</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">None</span></span></code></pre></div>



<p class="wp-block-paragraph">どちらを使っても意味は同じです。</p>



<p class="wp-block-paragraph"><code>#</code>を使ったコメントと違って、トリプルクオートは文字列として解釈されます。</p>



<p class="wp-block-paragraph">なので、厳密にいうとプログラム上無視されるわけではなく文字列として読み込まれることになります。</p>



<p class="wp-block-paragraph">そのため、以下のように複数行の文字列を変数に格納したい場合に使えます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># メール本文
body = """
お世話になっております。
株式会社 〇〇〇〇 の 〇〇です。
・・・
何卒、よろしくお願いいたします。
"""</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># メール本文</span></span>
<span class="line"><span style="color: #D4D4D4">body = </span><span style="color: #CE9178">&quot;&quot;&quot;</span></span>
<span class="line"><span style="color: #CE9178">お世話になっております。</span></span>
<span class="line"><span style="color: #CE9178">株式会社 〇〇〇〇 の 〇〇です。</span></span>
<span class="line"><span style="color: #CE9178">・・・</span></span>
<span class="line"><span style="color: #CE9178">何卒、よろしくお願いいたします。</span></span>
<span class="line"><span style="color: #CE9178">&quot;&quot;&quot;</span></span></code></pre></div>



<p class="wp-block-paragraph">以下の場合には「関数箇所のインデント」に合っていないので、インデントエラーになってしまいます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># ダブルクオートを使った場合
def double_quate():
"""
ここにコメントを書く
"""
    return None</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># ダブルクオートを使った場合</span></span>
<span class="line"><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">double_quate</span><span style="color: #D4D4D4">():</span></span>
<span class="line"><span style="color: #CE9178">&quot;&quot;&quot;</span></span>
<span class="line"><span style="color: #CE9178">ここにコメントを書く</span></span>
<span class="line"><span style="color: #CE9178">&quot;&quot;&quot;</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">return</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">None</span></span></code></pre></div>



<p class="wp-block-paragraph">ぱっと見で違和感があるので気づきやすいと思いますが、念のため理解しておくと良いでしょう。</p>



<p class="wp-block-paragraph">Python3.0 以降では、関数の引数や戻り値の「型」や「オブジェクトの種類」を明示するのに使われます。</p>



<p class="wp-block-paragraph">強制力はないので別の種類の「型」や「オブジェクト」が渡されたとしてもエラーにはなりませんが、コードを読む時の理解の助けにはなります。</p>



<p class="wp-block-paragraph">パラメータの後にコロン（<code>:</code>）と型名を記載し、アロー（<code>-&gt;</code>）の後に戻り値の型名を記載します。</p>



<p class="wp-block-paragraph">具体例な書き方は以下の通り。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>def int_to_string(param: int) -> str:
    return str(param)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">int_to_string</span><span style="color: #D4D4D4">(</span><span style="color: #9CDCFE">param</span><span style="color: #D4D4D4">: </span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4">) -&gt; </span><span style="color: #4EC9B0">str</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">return</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">str</span><span style="color: #D4D4D4">(param)</span></span></code></pre></div>



<p class="wp-block-paragraph">実は、関数アノテーションを入れたとしても実際の型検査や型強制は行われません。</p>



<p class="wp-block-paragraph">関数アノテーションを使うことによるメリットは、<strong>IDE などの静的型チェックツールで赤下線などが表示されることによりエラーチェックが強化される</strong>ことです。</p>



<p class="wp-block-paragraph">開発中に型系の齟齬に気づきやすくなるという点で有効だと考えれば良いと思います。</p>



<p class="wp-block-paragraph"><a href="https://peps.python.org/pep-0008/#inline-comments">Pythonの標準スタイルガイド（PEP8）</a>には、以下のようなコメントに関する記述ルールが記載されています。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><code>#</code>とコメントの間のスペース数</li>



<li>コードとコメントの間のスペース数</li>



<li><code>#</code>の数</li>



<li>コメントはコードと矛盾してはいけない</li>



<li>常にコードの変更時に更新する</li>
</ul>
</div></div>



<p class="wp-block-paragraph">ルールを破ってもエラーになりませんが、ルールを守ることで「違和感のない可読性の高いコード」を書くことができるようになります。</p>



<p class="wp-block-paragraph">以下、PEP8 に記載の推奨ルールをご紹介します。</p>



<p class="wp-block-paragraph"><code>#</code>の後にはスペース1つを入れます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># プログラミング言語を入力
code_type = "python"</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># プログラミング言語を入力</span></span>
<span class="line"><span style="color: #D4D4D4">code_type = </span><span style="color: #CE9178">&quot;python&quot;</span></span></code></pre></div>



<p class="wp-block-paragraph">上記の例では、<code>#</code>とプログラミング言語を入力の間のスペースは１つです。</p>



<p class="wp-block-paragraph">2つ以上のスペースを入れると間の抜けた感じになってしまうので、ここは統一しておきましょう。</p>



<p class="wp-block-paragraph">コードとコメントの間には「2つ以上のスペース」を開けることが推奨されています。</p>



<p class="wp-block-paragraph">なぜなら、スペースを入れることにより「コード」と「コメント」の境界線がパッと見で判断することができるからです。</p>



<p class="wp-block-paragraph">このほうが、コードレビュー時に断然読みやすい。</p>



<p class="wp-block-paragraph">例えば、以下の例ではコードの終わり（<code>"python"</code>）とコメントの間に2つのスペースを入れています。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>code_type = "python"  # プログラミング言語を入力</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">code_type = </span><span style="color: #CE9178">&quot;python&quot;</span><span style="color: #D4D4D4">  </span><span style="color: #6A9955"># プログラミング言語を入力</span></span></code></pre></div>



<p class="wp-block-paragraph">PEP8 では「2つ以上のスペース」とされていますが、私がこれまで見てきたコードでは3つ以上のスペースが開けられることはあまりない気がします。</p>



<p class="wp-block-paragraph">先頭の#は１つだけにします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># 正しいコメントの書き方

## 誤り
### 誤り</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># 正しいコメントの書き方</span></span>
<span class="line"></span>
<span class="line"><span style="color: #6A9955">## 誤り</span></span>
<span class="line"><span style="color: #6A9955">### 誤り</span></span></code></pre></div>



<p class="wp-block-paragraph">私は以前これを知らずに、マークダウンの見出しような雰囲気で<code>##</code>や<code>###</code>のように書いていましたが、PEP8 的には非推奨なので注意しましょう。</p>



<p class="wp-block-paragraph">これを知ってから、私は PEP8 に従った書き方に変えました。</p>



<p class="wp-block-paragraph">コメントは、コードの内容を説明するものでなければなりません。</p>



<p class="wp-block-paragraph">そのため矛盾したコメントは混乱を生むだけであって、書くべきではありません。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># xの値を減らす
x = x + 1</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955"># xの値を減らす</span></span>
<span class="line"><span style="color: #D4D4D4">x = x + </span><span style="color: #B5CEA8">1</span></span></code></pre></div>



<p class="wp-block-paragraph">上記のコードを見ると、「え、どういうこと！？」と感じるはずです。</p>



<p class="wp-block-paragraph">長文のコードを書いていると混乱してきて、変なコメントを書いてしまうこともあると思います。</p>



<p class="wp-block-paragraph">後から読んだ人が混乱してしまわないよう、コメントを入れる際には気をつけてみましょう。</p>



<p class="wp-block-paragraph">仕様変更・コード修正の際に、コードだけではなくコメントも更新しましょう。</p>



<p class="wp-block-paragraph">コードが正しければ、コメントは間違っていても正しく動いてしまいます。</p>



<p class="wp-block-paragraph">意外とコメントはないがしろにされてしまうことも多いので、こちらも後からコードを読む人の可読性を確保するためコメントもしっかりと更新するようにしましょう。</p>



<p class="wp-block-paragraph">以上のルールを守ることで、読みやすく保守しやすいプログラミングコードを開発することができます。</p>



<p class="wp-block-paragraph">ところが今回紹介したものだけでもかなり細かいルールだと感じた方は多いのではないでしょうか？</p>



<p class="wp-block-paragraph">そのような場合に便利なのが「フォーマッタ」です。</p>



<p class="wp-block-paragraph">フォーマッタとは PEP8 などに違反する部分を自動的に整形してくれるツールで、以下のようなものがあります。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>Black</li>



<li>isort</li>



<li>autopep8 </li>
</ul>
</div></div>



<p class="wp-block-paragraph">Visual Studio Code では、これらのフォーマッタを有効化しておくことで保存（Command + S）するたびに整形するよう設定することも可能です。</p>



<p class="wp-block-paragraph">私は Black と isort の組み合わせを好んで使っています。</p>



<p class="wp-block-paragraph">Black フォーマッタの詳しい導入方法は、以下の記事で解説しています。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/03/python-black-formatter-300x158.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/python-black-formatter/">【VSCode対応】PythonのBlackフォーマッタを使う方法</a>
						<span class="p-blogCard__excerpt">BlackはPythonのコードを整形してくれるツールです。 例えば次のような汚いコードがあったとします。 Pythondef calculate_sum(a,b): return a+b def multiply(x,y):ret&#8230;</span>					</div>
				</div>
			</div>
		</div>


<p class="wp-block-paragraph">ここまでご紹介したコメントの書き方を実践していただければ、かなり読みやすいコードがかけるようになっているはずです。</p>



<p class="wp-block-paragraph">今回はコメントに特化した内容をお伝えしていきましたが、コードは後から読み返す時間の方が多いため結構重要なポイントだと思います。</p>



<p class="wp-block-paragraph">ぜひ、今回の書き方をマスターしてコーディングスキルを上げていきましょう！</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Django REST framework】REST APIを開発する方法</title>
		<link>https://cfxlog.com/drf/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Fri, 07 Aug 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[API連携]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5226</guid>

					<description><![CDATA[このような疑問にお答えします。 Django では “Django REST framework”（以下、「DRF」とします） というフレームワークを使うことで、REST API を開発することができます。 最初に Dj [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-group is-style-crease"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>Django を使って REST API を開発したい！</li>
</ul>
</div></div>



<p class="wp-block-paragraph">このような疑問にお答えします。</p>



<p class="wp-block-paragraph">Django では “Django REST framework”（以下、「DRF」とします） というフレームワークを使うことで、REST API を開発することができます。</p>



<p class="wp-block-paragraph">最初に Django をインストールした上で、さらに DRF をインストールする流れです。</p>



<p class="wp-block-paragraph">本記事では以下の内容をお伝えします。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>API 開発に DRF を採用するメリット</li>

<li>DRF を使った API 開発の流れ</li>

<li>DRF をさらに使いこなす実装例</li>
</ul>
</div></div>



<p class="wp-block-paragraph">この記事さえご覧いただければ DRF の全体像を掴んでいただけるよう、内容を網羅して解説していきます。</p>



<p class="wp-block-paragraph">ただし分量が膨大になってしまう関係で、細かいトピックは別記事を用意しています。関連記事も併せてご覧いただくことで、より DRF を使いこなすことができるようになるはずです。</p>



<p class="is-style-icon_info wp-block-paragraph">ここでは「REST API がどのようなものか？」といったものは解説しません。</p>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset5 animation-fade rtoc_open default" data-id="5226" data-theme="SWELL CHILD">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji mokuji_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">DRFの主な機能</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-2">シリアライゼーション</a></li><li class="rtoc-item"><a href="#rtoc-3">ビューセットとルーター</a></li><li class="rtoc-item"><a href="#rtoc-4">認証と権限付与</a></li><li class="rtoc-item"><a href="#rtoc-5">ページネーションとフィルタリング</a></li><li class="rtoc-item"><a href="#rtoc-6">ブラウザブルAPI</a></li><li class="rtoc-item"><a href="#rtoc-7">バージョニング</a></li><li class="rtoc-item"><a href="#rtoc-8">セキュリティ</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-9">DRFを採用するメリット</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-10">Django と統合している</a></li><li class="rtoc-item"><a href="#rtoc-11">高度なシリアライゼーションが可能</a></li><li class="rtoc-item"><a href="#rtoc-12">細かく認証設定ができる</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-13">DRFを使ったAPI開発の流れ</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-14">① プロジェクトのセットアップ</a></li><li class="rtoc-item"><a href="#rtoc-15">② モデルの定義</a></li><li class="rtoc-item"><a href="#rtoc-16">③ シリアライザの作成</a></li><li class="rtoc-item"><a href="#rtoc-17">④ ビューの作成</a></li><li class="rtoc-item"><a href="#rtoc-18">⑤ ルーティングの設定</a></li><li class="rtoc-item"><a href="#rtoc-19">⑥ 認証と権限の設定</a></li><li class="rtoc-item"><a href="#rtoc-20">⑦ テスト</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-21">DRFをさらに使いこなす実装例</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-22">CORSヘッダーを付与する</a></li><li class="rtoc-item"><a href="#rtoc-23">API Key認証を追加する</a></li><li class="rtoc-item"><a href="#rtoc-24">画像アップロード機能を実装する</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-25">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">DRFの主な機能</h2>



<p class="wp-block-paragraph">まずは DRF がどのようなフレームワークかを解説します。</p>



<p class="wp-block-paragraph">API 開発のためのフレームワークには Python でいえば Flask, FastAPI などが、他の言語であれば NestJS, Spring Boot, Ruby on Rails などがあります。</p>



<p class="wp-block-paragraph">その中でも DRF を利用するメリットなどを理解して、技術選定の一助としてみてください。</p>



<p class="wp-block-paragraph">ここでは簡単に DRF で実装できる機能と、簡単な説明をしていきます。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li><strong>シリアライゼーション</strong></li>

<li><strong>ビューセットとルーター</strong></li>

<li><strong>認証と権限付与</strong></li>

<li><strong>ページネーションとフィルタリング</strong></li>

<li><strong>ブラウザブルAPI</strong></li>

<li><strong>バージョニング</strong></li>

<li><strong>セキュリティ</strong></li>
</ul>
</div></div>



<p class="wp-block-paragraph">それぞれ、掘り下げて解説します。</p>



<h3 id="rtoc-2"  class="wp-block-heading">シリアライゼーション</h3>



<p class="wp-block-paragraph">Django 内部で処理された Python オブジェクトを、JSON や XML などのフロントエンドで解釈がしやすい形式に変換することができます。</p>



<p class="wp-block-paragraph">この変換機能を「シリアライズ」と呼び、これが DRF の代表的な機能の一つになります。</p>



<h3 id="rtoc-3"  class="wp-block-heading">ビューセットとルーター</h3>



<p class="wp-block-paragraph">API のアクセス先となるエンドポイントを決定することができます。</p>



<p class="wp-block-paragraph">大元のフレームワークは Django を利用しているので、ビューとルーターはそれぞれ “views.py” と “urls.py” で制御することになります。</p>



<h3 id="rtoc-4"  class="wp-block-heading">認証と権限付与</h3>



<p class="wp-block-paragraph">Basic 認証、セッション認証、トークン認証を標準でサポートしています。</p>



<p class="wp-block-paragraph">また、”REST framework api key” などのサードパーティライブラリを使うことで、API Key 認証機能なども実装することができます。</p>



<h3 id="rtoc-5"  class="wp-block-heading">ページネーションとフィルタリング</h3>



<p class="wp-block-paragraph">大量のデータを小分けできる「ページネーション」が実装できます。</p>



<p class="wp-block-paragraph">これにより、レスポンス速度が向上したり、ユーザーがデータを簡単に見つけやすくできます。</p>



<p class="wp-block-paragraph">DRF では以下のようなページネーション種類を提供しています。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>LimitOffsetPagination</li>

<li>PageNumberPagination</li>

<li>CursorPagination</li>
</ul>
</div></div>



<p class="wp-block-paragraph">settings.py に記述すれば全体にページネーションを反映させることができますし、ビューごとにページネーションを個別設定することも可能です。</p>



<p class="wp-block-paragraph">また、特定のキーワードで検索したりといった「フィルタリング」も簡単に実装できます。</p>



<p class="wp-block-paragraph">フィルタリングバックエンドとしては、以下のようなものがあります。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>DjangoFilterBackend</li>

<li>SearchFilter</li>

<li>OrderingFilter</li>
</ul>
</div></div>



<p class="wp-block-paragraph">これらの詳細は、別記事で解説する予定です。</p>



<h3 id="rtoc-6"  class="wp-block-heading">ブラウザブルAPI</h3>



<p class="wp-block-paragraph">ブラウザから直接 API を閲覧できる機能です。</p>



<p class="wp-block-paragraph">これにより API の挙動を簡単に確認できるので、フロントエンド開発者や API 利用者にとっても理解しやすくなります。</p>



<p class="is-style-icon_info wp-block-paragraph">ブラウザブルAPIはデフォルト機能ですが、うまく動作しない場合には settings.py の DEFAULT_RENDERER_CLASSES に BrowsableAPIRenderer あるか確認してください。</p>



<h3 id="rtoc-7"  class="wp-block-heading">バージョニング</h3>



<p class="wp-block-paragraph">urls.py でバージョンごとにエンドポイントを切り替えることで、バージョンごとの管理が簡単に行えます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from django.urls import path, include

urlpatterns = [
    path('api/v1/', include('app_v1.urls')),  # v1のAPI
    path('api/v2/', include('app_v2.urls')),  # v2のAPI
]</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> django.urls </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> path, include</span></span>
<span class="line"></span>
<span class="line"><span style="color:#D4D4D4">urlpatterns = [</span></span>
<span class="line"><span style="color:#D4D4D4">    path(</span><span style="color:#CE9178">'api/v1/'</span><span style="color:#D4D4D4">, include(</span><span style="color:#CE9178">'app_v1.urls'</span><span style="color:#D4D4D4">)),  </span><span style="color:#6A9955"># v1のAPI</span></span>
<span class="line"><span style="color:#D4D4D4">    path(</span><span style="color:#CE9178">'api/v2/'</span><span style="color:#D4D4D4">, include(</span><span style="color:#CE9178">'app_v2.urls'</span><span style="color:#D4D4D4">)),  </span><span style="color:#6A9955"># v2のAPI</span></span>
<span class="line"><span style="color:#D4D4D4">]</span></span></code></pre></div>



<p class="wp-block-paragraph">バージョニング方法は、後日別記事で詳しく紹介する予定です。</p>



<h3 id="rtoc-8"  class="wp-block-heading">セキュリティ</h3>



<p class="wp-block-paragraph">CSRF 保護や CORS ヘッダーの管理など、セキュリティ対策が組み込まれています。</p>



<h2 id="rtoc-9"  class="wp-block-heading">DRFを採用するメリット</h2>



<p class="wp-block-paragraph">DRF を採用することで、以下のメリットが得られます。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>Django と統合している</li>

<li>高度なシリアライゼーションが可能</li>

<li>細かく認証設定ができる</li>
</ul>
</div></div>



<h3 id="rtoc-10"  class="wp-block-heading">Django と統合している</h3>



<p class="wp-block-paragraph">すでに Python や Django を使い慣れている方には、学習コストを抑えて導入ができます。</p>



<p class="wp-block-paragraph">また、Djangoのモデル、ユーザー認証、管理画面などがそのまま使えることも大きなメリットの一つです。</p>



<h3 id="rtoc-11"  class="wp-block-heading">高度なシリアライゼーションが可能</h3>



<p class="wp-block-paragraph">Django モデルから API に簡単に変換できる仕組みが備わっています。</p>



<p class="wp-block-paragraph">他のフレームワークでは、モデルの変換・複雑なデータモデルのサポート・フィールドレベルのカスタマイズなどが煩雑になりがちですが、Django を使うことでシンプルに記述できるようになります。</p>



<h3 id="rtoc-12"  class="wp-block-heading">細かく認証設定ができる</h3>



<p class="wp-block-paragraph">DRF では標準で「基本認証」「トークン認証」「OAuth」などをサポートしています。</p>



<p class="wp-block-paragraph">さらに、Django 標準で搭載されている「セッション管理」「CSRF」などのセキュリティ機能とも連動。</p>



<p class="wp-block-paragraph">ビューごとに異なる認証方法を採用したり、ユーザーやグループごとに認証方式を変えることもでき、柔軟性の高さが魅力です。</p>



<h2 id="rtoc-13"  class="wp-block-heading">DRFを使ったAPI開発の流れ</h2>



<p class="wp-block-paragraph">ここからは実際に DRF を使った API 開発の流れをお伝えします。</p>



<p class="wp-block-paragraph">基本的な流れとして、以下の流れで説明します。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>プロジェクトのセットアップ</li>

<li>モデルの定義</li>

<li>シリアライザの作成</li>

<li>ビューの作成</li>

<li>ルーティングの設定</li>

<li>認証と権限の設定</li>

<li>テスト</li>
</ul>
</div></div>



<h3 id="rtoc-14"  class="wp-block-heading">① プロジェクトのセットアップ</h3>



<p class="wp-block-paragraph">Django を開発環境にインストールします。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install django</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#CE9178"> django</span></span></code></pre></div>



<p class="wp-block-paragraph">続いて Django のプロジェクトをセットアップを行いましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>django-admin startproject projectname</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">django-admin</span><span style="color:#CE9178"> startproject</span><span style="color:#CE9178"> projectname</span></span></code></pre></div>



<p class="wp-block-paragraph">アプリケーションの作成を行いましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>cd projectname
python manage.py startapp api</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">cd</span><span style="color:#CE9178"> projectname</span></span>
<span class="line"><span style="color:#DCDCAA">python</span><span style="color:#CE9178"> manage.py</span><span style="color:#CE9178"> startapp</span><span style="color:#CE9178"> api</span></span></code></pre></div>



<p class="wp-block-paragraph">さらに、DRF を使用するため以下のコマンドを実行します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>pip install djangorestframework</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">pip</span><span style="color:#CE9178"> install</span><span style="color:#CE9178"> djangorestframework</span></span></code></pre></div>



<p class="wp-block-paragraph">settings.py に以下を追記して、DRF を使える状態にしましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>INSTALLED_APPS = [
    ...
    'rest_framework',
    'api',
    ...
]</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">INSTALLED_APPS = [</span></span>
<span class="line"><span style="color:#D4D4D4">    ...</span></span>
<span class="line"><span style="color:#CE9178">    'rest_framework'</span><span style="color:#D4D4D4">,</span></span>
<span class="line"><span style="color:#CE9178">    'api'</span><span style="color:#D4D4D4">,</span></span>
<span class="line"><span style="color:#D4D4D4">    ...</span></span>
<span class="line"><span style="color:#D4D4D4">]</span></span></code></pre></div>



<p class="wp-block-paragraph">これでセットアップは完了です。</p>



<h3 id="rtoc-15"  class="wp-block-heading">② モデルの定義</h3>



<p class="wp-block-paragraph">一般的な Django プロジェクトと同様、models.py に以下のような形で記載します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> django.db </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> models</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">class</span><span style="color:#4EC9B0"> Post</span><span style="color:#D4D4D4">(</span><span style="color:#4EC9B0">models</span><span style="color:#D4D4D4">.</span><span style="color:#4EC9B0">Model</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#D4D4D4">    title = models.CharField(</span><span style="color:#9CDCFE">max_length</span><span style="color:#D4D4D4">=</span><span style="color:#B5CEA8">100</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#D4D4D4">    content = models.TextField()</span></span>
<span class="line"><span style="color:#D4D4D4">    created_at = models.DateTimeField(</span><span style="color:#9CDCFE">auto_now_add</span><span style="color:#D4D4D4">=</span><span style="color:#569CD6">True</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#D4D4D4">    updated_at = models.DateTimeField(</span><span style="color:#9CDCFE">auto_now</span><span style="color:#D4D4D4">=</span><span style="color:#569CD6">True</span><span style="color:#D4D4D4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">    def</span><span style="color:#DCDCAA"> __str__</span><span style="color:#D4D4D4">(</span><span style="color:#9CDCFE">self</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#C586C0">        return</span><span style="color:#569CD6"> self</span><span style="color:#D4D4D4">.title</span></span></code></pre></div>



<p class="wp-block-paragraph">これをデータベースに適用するため、以下のコマンドを実行してマイグレーションを行いましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>python manage.py makemigrations
python manage.py migrate</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#DCDCAA">python</span><span style="color:#CE9178"> manage.py</span><span style="color:#CE9178"> makemigrations</span></span>
<span class="line"><span style="color:#DCDCAA">python</span><span style="color:#CE9178"> manage.py</span><span style="color:#CE9178"> migrate</span></span></code></pre></div>



<h3 id="rtoc-16"  class="wp-block-heading">③ シリアライザの作成</h3>



<p class="wp-block-paragraph">続いてレスポンスとして JSON などを返せるよう、アプリディレクトリ内に serializers.py を作成して以下のように記述しましょう。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ['id', 'title', 'content', 'created_at', 'updated_at']</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> rest_framework </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> serializers</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> .models </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> Post</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">class</span><span style="color:#4EC9B0"> PostSerializer</span><span style="color:#D4D4D4">(</span><span style="color:#4EC9B0">serializers</span><span style="color:#D4D4D4">.</span><span style="color:#4EC9B0">ModelSerializer</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#569CD6">    class</span><span style="color:#4EC9B0"> Meta</span><span style="color:#D4D4D4">:</span></span>
<span class="line"><span style="color:#D4D4D4">        model = Post</span></span>
<span class="line"><span style="color:#D4D4D4">        fields = [</span><span style="color:#CE9178">'id'</span><span style="color:#D4D4D4">, </span><span style="color:#CE9178">'title'</span><span style="color:#D4D4D4">, </span><span style="color:#CE9178">'content'</span><span style="color:#D4D4D4">, </span><span style="color:#CE9178">'created_at'</span><span style="color:#D4D4D4">, </span><span style="color:#CE9178">'updated_at'</span><span style="color:#D4D4D4">]</span></span></code></pre></div>



<h3 id="rtoc-17"  class="wp-block-heading">④ ビューの作成</h3>



<p class="wp-block-paragraph">先ほど作成したシリアライザを “views.py” 内で指定して、JSON 形式でレスポンスを行うように指定します。一覧表示用の<code>PostListView</code>と、詳細表示用の<code>PostDetailView</code>を両方作成します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from rest_framework.generics import ListAPIView, RetrieveAPIView
from .models import Post
from .serializers import PostSerializer

class PostListView(ListAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

class PostDetailView(RetrieveAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> rest_framework.generics </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> ListAPIView, RetrieveAPIView</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> .models </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> Post</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> .serializers </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> PostSerializer</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">class</span><span style="color:#4EC9B0"> PostListView</span><span style="color:#D4D4D4">(</span><span style="color:#4EC9B0">ListAPIView</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#D4D4D4">    queryset = Post.objects.all()</span></span>
<span class="line"><span style="color:#D4D4D4">    serializer_class = PostSerializer</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">class</span><span style="color:#4EC9B0"> PostDetailView</span><span style="color:#D4D4D4">(</span><span style="color:#4EC9B0">RetrieveAPIView</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#D4D4D4">    queryset = Post.objects.all()</span></span>
<span class="line"><span style="color:#D4D4D4">    serializer_class = PostSerializer</span></span></code></pre></div>



<h3 id="rtoc-18"  class="wp-block-heading">⑤ ルーティングの設定</h3>



<p class="wp-block-paragraph">さらに、エンドポイントの定義を行います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from django.urls import path
from .views import PostDetailView, PostListView

urlpatterns = [
    path('posts/', PostListView.as_view(), name='post-list'),
    path('posts/&lt;int:pk&gt;/', PostDetailView.as_view(), name='post-detail'),
]</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> django.urls </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> path</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> .views </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> PostDetailView, PostListView</span></span>
<span class="line"></span>
<span class="line"><span style="color:#D4D4D4">urlpatterns = [</span></span>
<span class="line"><span style="color:#D4D4D4">    path(</span><span style="color:#CE9178">'posts/'</span><span style="color:#D4D4D4">, PostListView.as_view(), </span><span style="color:#9CDCFE">name</span><span style="color:#D4D4D4">=</span><span style="color:#CE9178">'post-list'</span><span style="color:#D4D4D4">),</span></span>
<span class="line"><span style="color:#D4D4D4">    path(</span><span style="color:#CE9178">'posts/&lt;int:pk>/'</span><span style="color:#D4D4D4">, PostDetailView.as_view(), </span><span style="color:#9CDCFE">name</span><span style="color:#D4D4D4">=</span><span style="color:#CE9178">'post-detail'</span><span style="color:#D4D4D4">),</span></span>
<span class="line"><span style="color:#D4D4D4">]</span></span></code></pre></div>



<h3 id="rtoc-19"  class="wp-block-heading">⑥ 認証と権限の設定</h3>



<p class="wp-block-paragraph">settings.py に以下のような追記を行います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
    ...
]</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#D4D4D4">INSTALLED_APPS = [</span></span>
<span class="line"><span style="color:#D4D4D4">    ...</span></span>
<span class="line"><span style="color:#CE9178">    'rest_framework'</span><span style="color:#D4D4D4">,</span></span>
<span class="line"><span style="color:#CE9178">    'rest_framework.authtoken'</span><span style="color:#D4D4D4">,</span></span>
<span class="line"><span style="color:#D4D4D4">    ...</span></span>
<span class="line"><span style="color:#D4D4D4">]</span></span></code></pre></div>



<p class="wp-block-paragraph">さらに、urls.py にトークン認証のエンドポイントを追加。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    ...
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
    ...
]</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> django.urls </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> path</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> rest_framework.authtoken.views </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> obtain_auth_token</span></span>
<span class="line"></span>
<span class="line"><span style="color:#D4D4D4">urlpatterns = [</span></span>
<span class="line"><span style="color:#D4D4D4">    ...</span></span>
<span class="line"><span style="color:#D4D4D4">    path(</span><span style="color:#CE9178">'api-token-auth/'</span><span style="color:#D4D4D4">, obtain_auth_token, </span><span style="color:#9CDCFE">name</span><span style="color:#D4D4D4">=</span><span style="color:#CE9178">'api_token_auth'</span><span style="color:#D4D4D4">),</span></span>
<span class="line"><span style="color:#D4D4D4">    ...</span></span>
<span class="line"><span style="color:#D4D4D4">]</span></span></code></pre></div>



<p class="wp-block-paragraph">そして認証の詳細を定義するため、以下のコードを追記します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response

class ExampleView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'message': 'Hello, World!'
        }
        return Response(content)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> rest_framework.permissions </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> IsAuthenticated</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> rest_framework.views </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> APIView</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> rest_framework.response </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> Response</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">class</span><span style="color:#4EC9B0"> ExampleView</span><span style="color:#D4D4D4">(</span><span style="color:#4EC9B0">APIView</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#D4D4D4">    permission_classes = [IsAuthenticated]</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">    def</span><span style="color:#DCDCAA"> get</span><span style="color:#D4D4D4">(</span><span style="color:#9CDCFE">self</span><span style="color:#D4D4D4">, </span><span style="color:#9CDCFE">request</span><span style="color:#D4D4D4">, </span><span style="color:#9CDCFE">format</span><span style="color:#D4D4D4">=</span><span style="color:#569CD6">None</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#D4D4D4">        content = {</span></span>
<span class="line"><span style="color:#CE9178">            'message'</span><span style="color:#D4D4D4">: </span><span style="color:#CE9178">'Hello, World!'</span></span>
<span class="line"><span style="color:#D4D4D4">        }</span></span>
<span class="line"><span style="color:#C586C0">        return</span><span style="color:#D4D4D4"> Response(content)</span></span></code></pre></div>



<p class="wp-block-paragraph">IsAuthenticated を指定することで、トークン認証を有効化することができます。</p>



<h3 id="rtoc-20"  class="wp-block-heading">⑦ テスト</h3>



<p class="wp-block-paragraph">最後に test.py などに以下のようなテストコードを記載します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from rest_framework.test import APITestCase
from rest_framework import status
from django.urls import reverse
from .models import Post

class PostAPITest(APITestCase):
    def setUp(self):
        # テスト用のデータを準備
        Post.objects.create(title='Test Post 1', content='Test Content 1')
        Post.objects.create(title='Test Post 2', content='Test Content 2')

    def test_view_posts(self):
        url = reverse('post-list')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 2)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> rest_framework.test </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> APITestCase</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> rest_framework </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> status</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> django.urls </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> reverse</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> .models </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> Post</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">class</span><span style="color:#4EC9B0"> PostAPITest</span><span style="color:#D4D4D4">(</span><span style="color:#4EC9B0">APITestCase</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#569CD6">    def</span><span style="color:#DCDCAA"> setUp</span><span style="color:#D4D4D4">(</span><span style="color:#9CDCFE">self</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#6A9955">        # テスト用のデータを準備</span></span>
<span class="line"><span style="color:#D4D4D4">        Post.objects.create(</span><span style="color:#9CDCFE">title</span><span style="color:#D4D4D4">=</span><span style="color:#CE9178">'Test Post 1'</span><span style="color:#D4D4D4">, </span><span style="color:#9CDCFE">content</span><span style="color:#D4D4D4">=</span><span style="color:#CE9178">'Test Content 1'</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#D4D4D4">        Post.objects.create(</span><span style="color:#9CDCFE">title</span><span style="color:#D4D4D4">=</span><span style="color:#CE9178">'Test Post 2'</span><span style="color:#D4D4D4">, </span><span style="color:#9CDCFE">content</span><span style="color:#D4D4D4">=</span><span style="color:#CE9178">'Test Content 2'</span><span style="color:#D4D4D4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">    def</span><span style="color:#DCDCAA"> test_view_posts</span><span style="color:#D4D4D4">(</span><span style="color:#9CDCFE">self</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#D4D4D4">        url = reverse(</span><span style="color:#CE9178">'post-list'</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#D4D4D4">        response = </span><span style="color:#569CD6">self</span><span style="color:#D4D4D4">.client.get(url)</span></span>
<span class="line"><span style="color:#569CD6">        self</span><span style="color:#D4D4D4">.assertEqual(response.status_code, status.HTTP_200_OK)</span></span>
<span class="line"><span style="color:#569CD6">        self</span><span style="color:#D4D4D4">.assertEqual(</span><span style="color:#DCDCAA">len</span><span style="color:#D4D4D4">(response.data), </span><span style="color:#B5CEA8">2</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">これで基本的な API 作成は完了です。</p>



<h2 id="rtoc-21"  class="wp-block-heading">DRFをさらに使いこなす実装例</h2>



<p class="wp-block-paragraph">次のような DRF の標準機能を拡張する方法をお伝えします。</p>



<div class="wp-block-group has-border -border03"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<ul class="wp-block-list">
<li>CORS ヘッダーを付与する</li>

<li>API Key 認証を追加する</li>

<li>画像アップロード機能を実装する</li>
</ul>
</div></div>



<h3 id="rtoc-22"  class="wp-block-heading">CORSヘッダーを付与する</h3>



<p class="wp-block-paragraph">フロントエンドとして React などの JavaScript フレームワークを使う場合には、 CORS 対策を行うことがあります。</p>



<p class="wp-block-paragraph">以下の記事では、”django-cors-headers” を利用した実装方法をご紹介しています。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/03/python-django-rest-cors-300x158.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/python-django-rest-cors/">Django REST framework で CORS 対策をする方法</a>
						<span class="p-blogCard__excerpt">Django REST framework で CORS エラーが出ている… このような場合の対策をお伝えします。 Django REST framework（以下「DRF」とします）では、外部ライブラリを使うこ&#8230;</span>					</div>
				</div>
			</div>
		</div>


<h3 id="rtoc-23"  class="wp-block-heading">API Key認証を追加する</h3>



<p class="wp-block-paragraph">サードパーティライブラリ “restframework-api-key” を使えば、 API Key 認証機能を追加することができます。</p>



<p class="wp-block-paragraph">詳しい実装方法は、後日別記事で解説する予定です。</p>



<h3 id="rtoc-24"  class="wp-block-heading">画像アップロード機能を実装する</h3>



<p class="wp-block-paragraph">API に画像アップロード機能を実装するには、少し工夫が必要です。</p>



<p class="wp-block-paragraph">以下の記事で詳細を解説しましたので、ご覧ください。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/07/swell-eyecatch-noimg-300x158.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/django-drf-upload-image/">【Django REST framework】画像ファイルアップロード機能の実装方法</a>
						<span class="p-blogCard__excerpt">Django REST framework で画像アップロード機能を実装したい！ Django REST framework（以下、「DRF」とします）で画像アップロード機能を実装するには、いくつかのステ&#8230;</span>					</div>
				</div>
			</div>
		</div>


<h2 id="rtoc-25"  class="wp-block-heading">まとめ</h2>



<p class="wp-block-paragraph">Python で API 開発をする場合、真っ先に候補に上がるのが DRF になると思います。</p>



<p class="wp-block-paragraph">本記事では DRF の全体像をざっと見渡してきました。</p>



<p class="wp-block-paragraph">本ブログでは Python を中心としてプログラミングに関する情報を発信しています。</p>



<p class="wp-block-paragraph">ぜひ、他の記事にも目を通してみてください。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Django】テンプレート・静的ファイル完全ガイド｜継承・フィルタ・CSS/JS管理まで解説</title>
		<link>https://cfxlog.com/python-django-templates-guide/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Fri, 31 Jul 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Django]]></category>
		<guid isPermaLink="false">https://cfxlog.com/python-django-templates-guide/</guid>

					<description><![CDATA[<p><img src="https://cfxlog.com/wp-content/uploads/2026/08/python-django-templates-guide-1024x538.jpg" class="webfeedsFeaturedVisual" /></p>Djangoのテンプレートを初めて触ったとき、普通のHTMLよりも少しオブジェクト指向的な考え方が必要で、理解するまで少し時間がかかりました。 変数を埋め込むだけならまだしも、テンプレート継承やタグ・フィルタといった仕組 [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img src="https://cfxlog.com/wp-content/uploads/2026/08/python-django-templates-guide-1024x538.jpg" class="webfeedsFeaturedVisual" /></p>
<p class="wp-block-paragraph">Djangoのテンプレートを初めて触ったとき、普通のHTMLよりも少しオブジェクト指向的な考え方が必要で、理解するまで少し時間がかかりました。</p>



<p class="wp-block-paragraph">変数を埋め込むだけならまだしも、テンプレート継承やタグ・フィルタといった仕組みが加わると、「このHTMLはどこから来ているのか」を追うのに慣れが必要でした。</p>



<p class="wp-block-paragraph">この記事では、<strong>テンプレートの基本から、継承の仕組み、静的ファイルの管理方法</strong>までを解説します。</p>



<p class="wp-block-paragraph">ビューの基本がまだの方は、先にこちらを読んでおくとつながりがわかりやすいです。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/07/swell-eyecatch-noimg-300x158.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/python-django-views-guide/">【Django】ビュー・URLルーティング完全ガイド｜FBV・CBV・URLconfを徹底解説</a>
						<span class="p-blogCard__excerpt">Djangoのビューには、関数で書くFBV（Function Based View）と、クラスで書くCBV（Class Based View）の2種類があります。 最初にCBVを見たとき、正直よくわかりません&#8230;</span>					</div>
				</div>
			</div>
		</div>


<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset5 animation-fade rtoc_open default" data-id="5404" data-theme="SWELL CHILD">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji mokuji_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">Djangoテンプレートの基本</a></li><li class="rtoc-item"><a href="#rtoc-2">テンプレート継承の仕組み</a></li><li class="rtoc-item"><a href="#rtoc-3">静的ファイル（CSS・JS・画像）を管理する</a></li><li class="rtoc-item"><a href="#rtoc-4">正直、最近はあまり出番がない</a></li><li class="rtoc-item"><a href="#rtoc-5">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">Djangoテンプレートの基本</h2>



<p class="wp-block-paragraph">ビューから渡されたデータをHTMLに埋め込むには、<code>{{ }}</code>を使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">HTML</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>&lt;!-- articles/detail.html -->
&lt;h1>{{ article.title }}&lt;/h1>
&lt;p>{{ article.body }}&lt;/p></textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955">&lt;!-- articles/detail.html --&gt;</span></span>
<span class="line"><span style="color: #808080">&lt;</span><span style="color: #569CD6">h1</span><span style="color: #808080">&gt;</span><span style="color: #D4D4D4">{{ article.title }}</span><span style="color: #808080">&lt;/</span><span style="color: #569CD6">h1</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #808080">&lt;</span><span style="color: #569CD6">p</span><span style="color: #808080">&gt;</span><span style="color: #D4D4D4">{{ article.body }}</span><span style="color: #808080">&lt;/</span><span style="color: #569CD6">p</span><span style="color: #808080">&gt;</span></span></code></pre></div>



<p class="wp-block-paragraph">条件分岐やループには<code>{% %}</code>タグを使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">HTML</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>&lt;ul>
{% for article in articles %}
  &lt;li>{{ article.title }}&lt;/li>
{% empty %}
  &lt;li>記事がありません&lt;/li>
{% endfor %}
&lt;/ul></textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #808080">&lt;</span><span style="color: #569CD6">ul</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #D4D4D4">{% for article in articles %}</span></span>
<span class="line"><span style="color: #D4D4D4">  </span><span style="color: #808080">&lt;</span><span style="color: #569CD6">li</span><span style="color: #808080">&gt;</span><span style="color: #D4D4D4">{{ article.title }}</span><span style="color: #808080">&lt;/</span><span style="color: #569CD6">li</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #D4D4D4">{% empty %}</span></span>
<span class="line"><span style="color: #D4D4D4">  </span><span style="color: #808080">&lt;</span><span style="color: #569CD6">li</span><span style="color: #808080">&gt;</span><span style="color: #D4D4D4">記事がありません</span><span style="color: #808080">&lt;/</span><span style="color: #569CD6">li</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #D4D4D4">{% endfor %}</span></span>
<span class="line"><span style="color: #808080">&lt;/</span><span style="color: #569CD6">ul</span><span style="color: #808080">&gt;</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>{% empty %}</code>は、ループ対象が0件だったときに表示される特別な分岐です。件数チェックを別に書かなくていいので地味に便利です。</p>



<h2 id="rtoc-2"  class="wp-block-heading">テンプレート継承の仕組み</h2>



<p class="wp-block-paragraph">ヘッダーやフッターなど、全ページ共通の部分を毎回書くのは非効率です。Djangoでは<strong>テンプレート継承</strong>で、共通レイアウトを1つのファイルにまとめられます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">HTML</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>&lt;!-- base.html -->
&lt;html>
&lt;body>
  &lt;header>共通ヘッダー&lt;/header>
  {% block content %}{% endblock %}
  &lt;footer>共通フッター&lt;/footer>
&lt;/body>
&lt;/html></textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955">&lt;!-- base.html --&gt;</span></span>
<span class="line"><span style="color: #808080">&lt;</span><span style="color: #569CD6">html</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #808080">&lt;</span><span style="color: #569CD6">body</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #D4D4D4">  </span><span style="color: #808080">&lt;</span><span style="color: #569CD6">header</span><span style="color: #808080">&gt;</span><span style="color: #D4D4D4">共通ヘッダー</span><span style="color: #808080">&lt;/</span><span style="color: #569CD6">header</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #D4D4D4">  {% block content %}{% endblock %}</span></span>
<span class="line"><span style="color: #D4D4D4">  </span><span style="color: #808080">&lt;</span><span style="color: #569CD6">footer</span><span style="color: #808080">&gt;</span><span style="color: #D4D4D4">共通フッター</span><span style="color: #808080">&lt;/</span><span style="color: #569CD6">footer</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #808080">&lt;/</span><span style="color: #569CD6">body</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #808080">&lt;/</span><span style="color: #569CD6">html</span><span style="color: #808080">&gt;</span></span></code></pre></div>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">HTML</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>&lt;!-- articles/detail.html -->
{% extends "base.html" %}

{% block content %}
  &lt;h1>{{ article.title }}&lt;/h1>
  &lt;p>{{ article.body }}&lt;/p>
{% endblock %}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #6A9955">&lt;!-- articles/detail.html --&gt;</span></span>
<span class="line"><span style="color: #D4D4D4">{% extends &quot;base.html&quot; %}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">{% block content %}</span></span>
<span class="line"><span style="color: #D4D4D4">  </span><span style="color: #808080">&lt;</span><span style="color: #569CD6">h1</span><span style="color: #808080">&gt;</span><span style="color: #D4D4D4">{{ article.title }}</span><span style="color: #808080">&lt;/</span><span style="color: #569CD6">h1</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #D4D4D4">  </span><span style="color: #808080">&lt;</span><span style="color: #569CD6">p</span><span style="color: #808080">&gt;</span><span style="color: #D4D4D4">{{ article.body }}</span><span style="color: #808080">&lt;/</span><span style="color: #569CD6">p</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #D4D4D4">{% endblock %}</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>{% extends %}</code>で親テンプレートを指定し、<code>{% block %}</code>で「ここを子テンプレートの内容に差し替える」という穴を開けておく。この2つがセットで、「共通部分は1箇所、ページ固有の部分だけ書く」という構造が成り立ちます。</p>



<h2 id="rtoc-3"  class="wp-block-heading">静的ファイル（CSS・JS・画像）を管理する</h2>



<p class="wp-block-paragraph">CSSやJavaScript、画像は<strong>静的ファイル（static files）</strong>として扱います。テンプレート内で参照するには、まず先頭で<code>{% load static %}</code>を読み込みます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">HTML</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>{% load static %}
&lt;link rel="stylesheet" href="{% static 'css/style.css' %}">
&lt;img src="{% static 'images/logo.png' %}" alt="logo"></textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">{% load static %}</span></span>
<span class="line"><span style="color: #808080">&lt;</span><span style="color: #569CD6">link</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">rel</span><span style="color: #D4D4D4">=</span><span style="color: #CE9178">&quot;stylesheet&quot;</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">href</span><span style="color: #D4D4D4">=</span><span style="color: #CE9178">&quot;{% static &apos;css/style.css&apos; %}&quot;</span><span style="color: #808080">&gt;</span></span>
<span class="line"><span style="color: #808080">&lt;</span><span style="color: #569CD6">img</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">src</span><span style="color: #D4D4D4">=</span><span style="color: #CE9178">&quot;{% static &apos;images/logo.png&apos; %}&quot;</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">alt</span><span style="color: #D4D4D4">=</span><span style="color: #CE9178">&quot;logo&quot;</span><span style="color: #808080">&gt;</span></span></code></pre></div>



<p class="wp-block-paragraph">パスを直接書かずに<code>{% static %}</code>タグを通す理由は、本番環境でファイルの配信元が変わっても（CDNに置くなど）、テンプレート側を書き換えずに済むからです。</p>



<h2 id="rtoc-4"  class="wp-block-heading">正直、最近はあまり出番がない</h2>



<p class="wp-block-paragraph">ここまで基本を解説しましたが、正直に言うと、最近はNext.jsなどでフロントエンドを組むことが多く、Djangoのテンプレート機能に触れる機会自体が減っています。</p>



<p class="wp-block-paragraph">管理画面や社内ツールのような、凝ったフロントが不要な場面ではまだ十分現役です。ただ、フロントを別で作る構成が前提なら、無理に今すぐ深く学ばなくても、必要になったタイミングで後回しにして問題ないと思います。</p>



<h2 id="rtoc-5"  class="wp-block-heading">まとめ</h2>



<p class="wp-block-paragraph">Djangoのテンプレートは、変数埋め込み・タグ・継承の3つを押さえれば基本形は書けるようになります。静的ファイルは<code>{% static %}</code>タグを通すのが基本です。</p>



<p class="wp-block-paragraph">フロントをNext.js等で別に組む場合は優先度を下げても構いません。管理画面や社内ツールを素早く作りたいときに知っておくと役立ちます。</p>



<p class="wp-block-paragraph">Django全体のロードマップに戻りたい方はこちらからどうぞ。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/07/swell-eyecatch-noimg-300x158.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/python-django-guide/">Django完全入門ガイド｜MTVの基本から認証・API・デプロイまで全ステップ解説</a>
						<span class="p-blogCard__excerpt">Djangoって何から始めればいいの？ MTVの構造がよくわからない 認証やAPI連携、本番デプロイまで一通り学びたい このような疑問にお答えします。 Djangoは、Pythonで書&#8230;</span>					</div>
				</div>
			</div>
		</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>【Django】モデル・マイグレーション完全ガイド｜フィールド設計からリレーションまで徹底解説</title>
		<link>https://cfxlog.com/python-django-models-guide/</link>
		
		<dc:creator><![CDATA[CFXLOG]]></dc:creator>
		<pubDate>Fri, 31 Jul 2026 15:00:00 +0000</pubDate>
				<category><![CDATA[Django]]></category>
		<guid isPermaLink="false">https://cfxlog.com/?p=5095</guid>

					<description><![CDATA[Djangoに触り始めた頃、モデルの前にまずデータベースそのものをよく知りませんでした。 モデルのクラス定義自体はPythonなので読めます。ただ、フィールドの引数に何を設定できるのか、それがDB側でどういう意味を持つの [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Djangoに触り始めた頃、モデルの前にまずデータベースそのものをよく知りませんでした。</p>



<p class="wp-block-paragraph">モデルのクラス定義自体はPythonなので読めます。ただ、フィールドの引数に何を設定できるのか、それがDB側でどういう意味を持つのかがわからず、最初はそこでつまずきました。</p>



<p class="wp-block-paragraph">この記事では、<strong>モデルの基本的な書き方から、よく使うフィールドの種類、リレーション設計、マイグレーションの仕組み</strong>までを解説します。</p>



<p class="wp-block-paragraph">Djangoのプロジェクト構成がまだの方は、先にこちらを読んでおくとスムーズです。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/03/python-django-project-setup-300x157.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/python-django-project-setup/">【Django】プロジェクトとアプリの設定方法まとめ</a>
						<span class="p-blogCard__excerpt">Djangoの開発を始めるための準備が知りたい！ 普通にPythonでコーディングするのと違って、Djangoの開発では細々した準備が必要です。 内容をざっと列挙すると以下の通&#8230;</span>					</div>
				</div>
			</div>
		</div>


<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset5 animation-fade rtoc_open default" data-id="5095" data-theme="SWELL CHILD">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji mokuji_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">Djangoモデルとは何か</a></li><li class="rtoc-item"><a href="#rtoc-2">フィールドの引数、最初はここでつまずいた</a></li><li class="rtoc-item"><a href="#rtoc-3">よく使うフィールドタイプ</a></li><li class="rtoc-item"><a href="#rtoc-4">テーブル同士をつなぐ：リレーション設計</a><ul class="rtoc-mokuji mokuji_none level-2"><li class="rtoc-item"><a href="#rtoc-5">フィールド設計に固定ルールは持っていない</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-6">マイグレーションを実行する</a></li><li class="rtoc-item"><a href="#rtoc-7">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">Djangoモデルとは何か</h2>



<p class="wp-block-paragraph">Djangoのモデルは、データベースのテーブルをPythonのクラスとして表現したものです。モデルクラス1つが、テーブル1つに対応します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    published_at = models.DateTimeField(auto_now_add=True)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> django.db </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> models</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">class</span><span style="color:#4EC9B0"> Article</span><span style="color:#D4D4D4">(</span><span style="color:#4EC9B0">models</span><span style="color:#D4D4D4">.</span><span style="color:#4EC9B0">Model</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#D4D4D4">    title = models.CharField(</span><span style="color:#9CDCFE">max_length</span><span style="color:#D4D4D4">=</span><span style="color:#B5CEA8">100</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#D4D4D4">    body = models.TextField()</span></span>
<span class="line"><span style="color:#D4D4D4">    published_at = models.DateTimeField(</span><span style="color:#9CDCFE">auto_now_add</span><span style="color:#D4D4D4">=</span><span style="color:#569CD6">True</span><span style="color:#D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph">クラス変数の1つ1つがテーブルのカラムになります。<code>CharField</code>や<code>TextField</code>といった型の指定が、SQLで言う<code>VARCHAR</code>や<code>TEXT</code>にあたります。SQLを自分で書く必要はありません。</p>



<h2 id="rtoc-2"  class="wp-block-heading">フィールドの引数、最初はここでつまずいた</h2>



<p class="wp-block-paragraph">フィールドにはそれぞれ引数があります。<code>CharField(max_length=100)</code>の<code>max_length</code>のような部分です。</p>



<p class="wp-block-paragraph">僕がつまずいたのはここでした。DBを触ったことがなかったので、「なぜ文字列に長さの上限を指定する必要があるのか」からしてピンときていませんでした。よく使う引数だけ、先に押さえておきます。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>引数</th><th>意味</th></tr></thead><tbody><tr><td>max_length</td><td>文字列の最大長（CharFieldで必須）</td></tr><tr><td>null</td><td>DB側でNULLを許可するか</td></tr><tr><td>blank</td><td>フォーム入力で空欄を許可するか</td></tr><tr><td>default</td><td>デフォルト値</td></tr><tr><td>unique</td><td>値の重複を許可しないか</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">特に<code>null</code>と<code>blank</code>は名前が似ていて紛らわしいポイントです。<code>null</code>はDBの制約、<code>blank</code>はフォームバリデーションの話。役割が違うので、両方Trueにしたい場面以外は分けて考えるようにしています。</p>



<h2 id="rtoc-3"  class="wp-block-heading">よく使うフィールドタイプ</h2>



<p class="wp-block-paragraph">実務でよく使うフィールドはそれほど多くありません。まずはこのあたりを覚えておけば大抵の場面に対応できます。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>フィールド</th><th>用途</th></tr></thead><tbody><tr><td>CharField</td><td>短い文字列（名前・タイトルなど）</td></tr><tr><td>TextField</td><td>長い文字列（本文など）</td></tr><tr><td>IntegerField</td><td>整数</td></tr><tr><td>BooleanField</td><td>True / False</td></tr><tr><td>DateTimeField</td><td>日時</td></tr><tr><td>ForeignKey</td><td>他のテーブルとの多対1のリレーション</td></tr></tbody></table></figure>



<h2 id="rtoc-4"  class="wp-block-heading">テーブル同士をつなぐ：リレーション設計</h2>



<p class="wp-block-paragraph">テーブル同士を関連づけるには<code>ForeignKey</code>を使います。「1人のユーザーが複数の記事を書く」というような、多対1の関係を表現できます。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Python</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>from django.conf import settings
from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="articles",
    )</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> django.conf </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> settings</span></span>
<span class="line"><span style="color:#C586C0">from</span><span style="color:#D4D4D4"> django.db </span><span style="color:#C586C0">import</span><span style="color:#D4D4D4"> models</span></span>
<span class="line"></span>
<span class="line"><span style="color:#569CD6">class</span><span style="color:#4EC9B0"> Article</span><span style="color:#D4D4D4">(</span><span style="color:#4EC9B0">models</span><span style="color:#D4D4D4">.</span><span style="color:#4EC9B0">Model</span><span style="color:#D4D4D4">):</span></span>
<span class="line"><span style="color:#D4D4D4">    title = models.CharField(</span><span style="color:#9CDCFE">max_length</span><span style="color:#D4D4D4">=</span><span style="color:#B5CEA8">100</span><span style="color:#D4D4D4">)</span></span>
<span class="line"><span style="color:#D4D4D4">    author = models.ForeignKey(</span></span>
<span class="line"><span style="color:#D4D4D4">        settings.AUTH_USER_MODEL,</span></span>
<span class="line"><span style="color:#9CDCFE">        on_delete</span><span style="color:#D4D4D4">=models.CASCADE,</span></span>
<span class="line"><span style="color:#9CDCFE">        related_name</span><span style="color:#D4D4D4">=</span><span style="color:#CE9178">"articles"</span><span style="color:#D4D4D4">,</span></span>
<span class="line"><span style="color:#D4D4D4">    )</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>on_delete</code>は、参照先（ここではユーザー）が削除されたときの挙動です。<code>CASCADE</code>を指定すると、ユーザーが削除された時に紐づく記事も一緒に削除されます。<code>related_name</code>を指定しておくと、ユーザー側から<code>user.articles.all()</code>のように逆方向にたどれるようになります。</p>



<h3 id="rtoc-5"  class="wp-block-heading">フィールド設計に固定ルールは持っていない</h3>



<p class="wp-block-paragraph">「このケースは必ずこう設計する」という固定のルールは、正直あまり持っていません。実際の運用を考えて、そのつど判断するようにしています。</p>



<p class="wp-block-paragraph">たとえば同じ「日付」でも、後から変更されうるデータなのか、記録として残すだけのデータなのかで、<code>null</code>を許可するかどうかの判断は変わります。設計を先に完璧に詰めるより、実際にどう使われるかをイメージしながら決めるほうが、結果的にうまくいく感覚があります。</p>



<h2 id="rtoc-6"  class="wp-block-heading">マイグレーションを実行する</h2>



<p class="wp-block-paragraph">モデルを書いただけでは、まだDBにテーブルは作られません。<strong>マイグレーション</strong>という仕組みを通して、モデルの定義をDBに反映します。</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:16px 0 0 16px;width:100%;text-align:left;background-color:#1e1e1e"><span style="background:#c7c7c7;padding:0.3rem 0.5rem 0.2rem;border-radius:1rem;font-size:0.8em;line-height:1;height:1.25rem;text-align:center;display:inline-flex;align-items:center;justify-content:center;color:#1e1e1e">Bash</span></span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly># モデルの変更内容から、マイグレーションファイルを生成
python manage.py makemigrations

# 生成されたマイグレーションをDBに適用
python manage.py migrate</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color:#1E1E1E;color:#D4D4D4" tabindex="0"><code><span class="line"><span style="color:#6A9955"># モデルの変更内容から、マイグレーションファイルを生成</span></span>
<span class="line"><span style="color:#DCDCAA">python</span><span style="color:#CE9178"> manage.py</span><span style="color:#CE9178"> makemigrations</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A9955"># 生成されたマイグレーションをDBに適用</span></span>
<span class="line"><span style="color:#DCDCAA">python</span><span style="color:#CE9178"> manage.py</span><span style="color:#CE9178"> migrate</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>makemigrations</code>が「変更内容の差分」を記録したファイルを作り、<code>migrate</code>がそれを実際にDBへ適用する。この2段階に分かれているおかげで、適用前に差分の内容を確認できます。</p>



<h2 id="rtoc-7"  class="wp-block-heading">まとめ</h2>



<p class="wp-block-paragraph">Djangoのモデルは、SQLを直接書かなくてもDBを操作できる仕組みです。フィールドの型・引数・リレーションの基本を押さえれば、あとは実際の運用に合わせて設計を調整していけば十分です。</p>



<p class="wp-block-paragraph">DBを触ったことがない方にとっては、Djangoのモデルを通すことで、直感的にDBの考え方を学べるはずです。僕自身、DBの知識はDjangoのモデルを書きながら身についていきました。</p>



<p class="wp-block-paragraph">モデルが書けるようになったら、次はそのデータを画面に表示するビューとURLルーティングに進みましょう。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/07/swell-eyecatch-noimg-300x158.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/python-django-views-guide/">【Django】ビュー・URLルーティング完全ガイド｜FBV・CBV・URLconfを徹底解説</a>
						<span class="p-blogCard__excerpt">Djangoのビューには、関数で書くFBV（Function Based View）と、クラスで書くCBV（Class Based View）の2種類があります。 最初にCBVを見たとき、正直よくわかりません&#8230;</span>					</div>
				</div>
			</div>
		</div>


<p class="wp-block-paragraph">Django全体のロードマップに戻りたい方はこちらからどうぞ。</p>


<div class="swell-block-postLink">			<div class="p-blogCard -internal" data-type="type1" data-onclick="clickLink">
				<div class="p-blogCard__inner">
					<span class="p-blogCard__caption">あわせて読みたい</span>
					<div class="p-blogCard__thumb c-postThumb"><figure class="c-postThumb__figure"><img decoding="async" src="https://cfxlog.com/wp-content/uploads/2026/07/swell-eyecatch-noimg-300x158.jpg" alt="" class="c-postThumb__img u-obf-cover" width="320" height="180"></figure></div>					<div class="p-blogCard__body">
						<a class="p-blogCard__title" href="https://cfxlog.com/python-django-guide/">Django完全入門ガイド｜MTVの基本から認証・API・デプロイまで全ステップ解説</a>
						<span class="p-blogCard__excerpt">Djangoって何から始めればいいの？ MTVの構造がよくわからない 認証やAPI連携、本番デプロイまで一通り学びたい このような疑問にお答えします。 Djangoは、Pythonで書&#8230;</span>					</div>
				</div>
			</div>
		</div>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
