<?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>「f-string」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/f-string/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sat, 14 Mar 2026 22:06:32 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>「f-string」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】テンプレート文字列 t-string の使い方</title>
		<link>https://tech.nkhn37.net/python-t-string-basic/</link>
					<comments>https://tech.nkhn37.net/python-t-string-basic/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Thu, 22 Jan 2026 20:00:00 +0000</pubDate>
				<category><![CDATA[文字列]]></category>
		<category><![CDATA[f-string]]></category>
		<category><![CDATA[Python 3.14]]></category>
		<category><![CDATA[t-string]]></category>
		<category><![CDATA[テンプレート文字列]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=13296</guid>

					<description><![CDATA[Python のテンプレート文字列（t-string）の使い方の基本について解説します。 テンプレート文字列 t-string テンプレート文字列 t-string とは t-string とは、Python 3.14  [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Python の<span class="jinr-d--text-color d--marker1 d--bold">テンプレート文字列（t-string）</span>の使い方の基本について解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">テンプレート文字列 t-string</h2>



<h3 class="wp-block-heading jinr-heading d--bold">テンプレート文字列 t-string とは</h3>



<p class="wp-block-paragraph"><span class="jinr-d--text-color d--marker1 d--bold">t-string</span> とは、Python 3.14 で新しく追加された<span class="jinr-d--text-color d--marker1 d--bold">テンプレート文字列</span>のための構文です。t-string は、以下のような文字列のことで、文字列をフォーマットするための f-string とよく似ていますが、最大の特徴は式の内容を保持したまま、文字列としてはまだフォーマットされない点です。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">t"Hello {name}"
</pre>



<p class="wp-block-paragraph">上記のように書いても <code>name</code> の値は即時に文字列には変換されません。t-string は、完成した文字列を作るものではなく、後から評価・処理されることを前提としたテンプレートを生成するものです。</p>



<p class="wp-block-paragraph">この記事では、テンプレート文字列 t-string の基本的な使い方や関連する型の構造などについて紹介します。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox6 ">
			<i class="jif jin-ifont-v2books" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph">フォーマットのための f-string については「<a href="https://tech.nkhn37.net/python-str-format-f-string/" target="_blank" rel="noreferrer noopener">formatやf-stringを用いて文字列をフォーマットする方法</a>」を参考にしてください。</p>
</div>
		</div></section>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--heading-iconbox1 ">
			<div class="a--heading-iconbox-title">
			<div class="a--iconbox-title-icon"><i class="jif jin-ifont-caution" aria-hidden="true"></i></div>
			<div class="a--iconbox-title-text">注意点</div>
			</div>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph">t-string を使用するには、Python 3.14 以降である必要があるので注意してください。</p>
</div>
		</div></section>



<h3 class="wp-block-heading jinr-heading d--bold">なぜ t-string が必要になるのか</h3>



<p class="wp-block-paragraph">t-string は、<a href="https://peps.python.org/pep-0750/" target="_blank" rel="noreferrer noopener">PEP 750</a> で提案されて取り込まれた構文です。文字列フォーマットのための f-string は非常に便利な構文ですが「文字列が即時評価される」という性質があり、もともとどういった文字列の中に何が埋め込まれたのかが後からは分からないという特徴があります。</p>



<p class="wp-block-paragraph">f-string は多くの場合で問題になりませんが、次のようなケースでは注意が必要です。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--simple-box1  "><div class="c--simple-box-inner">
<ul class="wp-block-list jinr-list">
<li>SQL や HTML に悪意のある文字列が取り込まれないように安全に処理したい。（SQL インジェクションやクロスサイトスクリプティング（XSS）の対策）</li>



<li>ユーザー入力を含む文字列をそのまま評価したくない。</li>



<li>ライブラリでテンプレートを引数で受け取り処理したい。</li>
</ul>
</div></div></section>



<p class="wp-block-paragraph">これまでは、上記には独自に対応する必要がありましたが、t-string は「文字列化されていないテンプレート」という概念を Python 標準の文法とし、この課題を解決するために導入されています。</p>



<h2 class="wp-block-heading jinr-heading d--bold">t-string の基本的な使い方</h2>



<h3 class="wp-block-heading jinr-heading d--bold">基本的な使い方</h3>



<p class="wp-block-paragraph">t-string の基本構文は、文字列リテラルの前に「<code>t</code>」をつけるだけです。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def main():
    user = "太郎"
    age = 30

    # t-string の使い方 例
    template = t"User: {user}, Age: {age}"

    # t-string の内容を表示
    print(f"template = {template}")

if __name__ == "__main__":
    main()</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
template = Template(strings=('User: ', ', Age: ', ''), interpolations=(Interpolation('太郎', 'user', None, ''), Interpolation(30, 'age', None, '')))</pre>



<p class="wp-block-paragraph">f-string と非常によく似ています。<code>{}</code> を使用してプレースホルダを記述し、用意した変数（例では、<code>user</code> や <code>age</code>）を渡します。</p>



<p class="wp-block-paragraph">返却値を <code>template</code> という変数に入れて表示してみていますが、<span class="jinr-d--text-color d--marker1 d--bold"><code>Template</code></span> 型になっているということが分かります。また、<code>Template</code> 型の中には、<span class="jinr-d--text-color d--marker1 d--bold"><code>Interpolation</code></span> 型というものも含まれることが分かります。これらの型については、後ほど説明していきます。</p>



<h3 class="wp-block-heading jinr-heading d--bold">t-string は文字列に変換されない</h3>



<p class="wp-block-paragraph">t-string の使い方は、f-string と同様で非常に簡単ですが、上記の例のポイントとしては、<span class="jinr-d--text-color d--marker1 d--bold">t-string を用意した時点で中の式は自動的に文字列には変換されない</span>点です。上記の例でいうと <code>user</code> や <code>age</code> の値は取得されますが、文字列としては展開されません。</p>



<p class="wp-block-paragraph">t-string は式と文字列部分を分離したまま保持します。つまり、「文字列を作る」ためではなく、「文字列の設計図を作る」構文と理解すると分かりやすいかと思います。</p>



<p class="wp-block-paragraph">この性質により以下のようなメリットがあります。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--simple-box1  "><div class="c--simple-box-inner">
<ul class="wp-block-list jinr-list">
<li>意図しないコードの実行を防ぎセキュリティ上のリスクを下げる実装をすることができる。</li>



<li>評価タイミングを呼び出した側に委ねることができる。</li>
</ul>
</div></div></section>



<p class="wp-block-paragraph">このように、t-string は「安全に扱えるテンプレート」を実現できます。</p>



<h3 class="wp-block-heading jinr-heading d--bold">t-string の型を深堀する</h3>



<p class="wp-block-paragraph">f-string は結果として <code>str</code> となりますが、t-string は単なる <code>str</code> ではありません。内部的には、テンプレートとしての構造を持ったオブジェクトが生成されます。</p>



<p class="wp-block-paragraph">ここでは、その型構造について、以下の例を使いながら紹介していきます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def main():
    user = "太郎"
    age = 30
    height = 1.72

    # t-string を作成
    template = t"User={user!r}, Age next year={age + 1}, Height={height:.2f}m"

    # t-string の内容を表示
    print(f"template = {template}\n")

    # strings, interpolations, values の内容を表示
    print(f"template.strings = {template.strings}\n")

    print("template.interpolations:")
    for i, interp in enumerate(template.interpolations):
        print(f"  [{i}]")
        print(f"    value        = {interp.value!r}")
        print(f"    expression   = {interp.expression!r}")
        print(f"    conversion   = {interp.conversion!r}")
        print(f"    format_spec  = {interp.format_spec!r}\n")

    print(f"template.values = {template.values}")

if __name__ == "__main__":
    main()</pre>



<h4 class="wp-block-heading jinr-heading d--bold"><code>Template</code> 型</h4>



<p class="wp-block-paragraph">t-string の返却は、<span class="jinr-d--text-color d--marker1 d--bold"><code>Template</code></span> 型となっています。具体的には、<code>string.templatelib.Template</code> です。<code>Template</code> は以下の構造を持ちます。</p>



<ul class="wp-block-list jinr-list">
<li><code>strings</code>：テンプレート内の固定文字列部分のタプル</li>



<li><code>interpolations</code>：<code>strings</code> 要素間の補間データ（<code>Interpolation</code>）のタプル</li>



<li><code>values</code>：式を評価した結果の値のタプル</li>
</ul>



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



<pre class="EnlighterJSRAW" data-enlighter-language="abap" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">template.strings = ('User=', ', Age next year=', ', Height=', 'm')

template.interpolations:
  [0]
    value        = '太郎'
    expression   = 'user'
    conversion   = 'r'
    format_spec  = ''

  [1]
    value        = 31
    expression   = 'age + 1'
    conversion   = None
    format_spec  = ''

  [2]
    value        = 1.72
    expression   = 'height'
    conversion   = None
    format_spec  = '.2f'

template.values = ('太郎', 31, 1.72)</pre>



<p class="wp-block-paragraph">上記の結果を見てみると <code>len(strings) == len(interpolations) + 1</code> という関係が成り立っているので、<code>strings</code> の要素の間に <code>interpolations</code> が挟まれている構造になっていることが分かるかと思います。また、<code>values</code> で各変数の部分にどのような値が埋め込まれるのかを確認できます。 </p>



<h4 class="wp-block-heading jinr-heading d--bold"><code>Interpolation</code> 型</h4>



<p class="wp-block-paragraph"><code>interpolations</code> の要素となっている <span class="jinr-d--text-color d--marker1 d--bold"><code>Interpolation</code></span> 型 についても要素を確認しておきましょう。具体的には、<code>string.templatelib.Interpolation</code> です。</p>



<ul class="wp-block-list jinr-list">
<li><code>value</code>：式を評価した結果の値</li>



<li><code>expression</code>：元の式を文字列として保持したもの</li>



<li><code>conversion</code>：変換指定子（<code>!r</code> / <code>!s</code> / <code>!a</code>）</li>



<li><code>format_spec</code>：書式指定文字列（<code>:</code> 以降に記載）</li>
</ul>



<p class="wp-block-paragraph"><code>value</code> は式を評価した結果の値を確認できます。また、結果がどのような式により計算されたかについては <code>expression</code> で文字列として確認できます。これは、式レベルで妥当性を評価する際に使用できます。</p>



<p class="wp-block-paragraph">変換指定子である <code>conversion</code> や書式指定文字列 <code>format_spec</code> は f-string でも指定できる要素です。t-string の特徴の通り、これらの変換はまだ適用されていません。テンプレートを受け取った側がどのような処理をするか判断をして使用します。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox5 ">
			<i class="jif jin-ifont-v2speaker" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph"><strong>【変換指定子】</strong></p>



<p class="wp-block-paragraph">変換指定子は補間対象の値をどの文字列表現に変換するかを指定するための記法です。</p>



<ul class="wp-block-list jinr-list">
<li><code>!r</code>：<code>repr(value)</code></li>



<li><code>!s</code>：<code>str(value)</code></li>



<li><code>!a</code>：<code>ascii(value)</code></li>
</ul>



<p class="wp-block-paragraph"><strong>【書式指定文字列】</strong></p>



<p class="wp-block-paragraph">書式指定文字列は、数値や文字列の表示形式を細かく制御するための指定文字列です。以下は例になります。</p>



<ul class="wp-block-list jinr-list">
<li><code>.2f</code>：小数点以下 2 桁</li>



<li><code>&gt;10</code>：右寄せ・桁数 10</li>



<li><code>0=10</code>：ゼロ埋め・桁数 10</li>
</ul>
</div>
		</div></section>



<h3 class="wp-block-heading jinr-heading d--bold">t-string の使いどころ</h3>



<p class="wp-block-paragraph">t-string がテンプレートの構造を保持する構造であるということが分かったかと思います。f-string との使い分けを記載すると以下のようになります。</p>



<ul class="wp-block-list jinr-list">
<li>”最終的な文字列がほしい” ⇒ f-string</li>



<li>&#8220;文字列化前に、値を安全に処理したい&#8221; ⇒ t-string</li>
</ul>



<p class="wp-block-paragraph">例えば、ユーザー入力に対して SQL 実行や HTML レンダリングをするような関数やメソッドを作成したとしましょう。この時、引数に <code>str</code> を受け取ると、その文字列に悪意のある文字列が含まれているかを判断するのは大変です。</p>



<p class="wp-block-paragraph">このような際に、関数やメソッドの引数を t-string（<code>Template</code> 型）を受け取るような形式にしておけば、受け取った側で適切な処理をした上で文字列として活用することができ、SQL インジェクションや XSS の脆弱性に対策した処理をすることが可能です。</p>



<h2 class="wp-block-heading jinr-heading d--bold">まとめ</h2>



<p class="wp-block-paragraph">Python の<span class="jinr-d--text-color d--marker1 d--bold">テンプレート文字列（t-string）</span>の使い方の基本について解説しました。</p>



<p class="wp-block-paragraph">t-string とは、Python 3.14 で新しく追加されたテンプレート文字列のための構文です。t-string は式と文字列部分を分離して保持し、まだ文字列として変換されていない構造を保持します。この性質により「意図しないコードの実行を防ぎセキュリティ上のリスクを防ぐ安全な処理を実装しやすい」「評価タイミングを呼び出した側に委ねることができる」といったメリットがあります。</p>



<p class="wp-block-paragraph">t-string は、<code>Template</code> 型となっており、<code>Interpolation</code> 型を含むような構造になっており、その概要についても紹介しました。</p>



<p class="wp-block-paragraph">t-string は、安全な関数やメソッドを構築する際に非常に便利なものであるため、うまく活用してみてほしいと思います。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box8  "><div class="a--simple-box-title d--bold">ソースコード</div><div class="c--simple-box-inner">
<p class="wp-block-paragraph">上記で紹介しているソースコードについては&nbsp;<a href="https://github.com/nkhn37/python-tech-sample-source/tree/main/python-basic/string/t-string" target="_blank" rel="noreferrer noopener">GitHub</a>&nbsp;にて公開しています。参考にしていただければと思います。</p>
</div></div></section>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/python-t-string-basic/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】formatやf-stringを用いて文字列をフォーマットする方法</title>
		<link>https://tech.nkhn37.net/python-str-format-f-string/</link>
					<comments>https://tech.nkhn37.net/python-str-format-f-string/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Sun, 02 May 2021 00:00:00 +0000</pubDate>
				<category><![CDATA[文字列]]></category>
		<category><![CDATA[f-string]]></category>
		<category><![CDATA[format]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=1464</guid>

					<description><![CDATA[Python で文字列をフォーマットする方法を解説します。 文字列をフォーマットする方法 Python で文字列を扱う際に、変数の値を埋め込んで出力用の文字列を作るような場面はよくあります。このような場合、文字列を簡潔に [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Python で<span class="jinr-d--text-color d--marker1 d--bold">文字列をフォーマットする方法</span>を解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">文字列をフォーマットする方法</h2>



<p class="wp-block-paragraph">Python で文字列を扱う際に、変数の値を埋め込んで出力用の文字列を作るような場面はよくあります。このような場合、文字列を簡潔にフォーマットできると便利です。</p>



<p class="wp-block-paragraph">Python では、代表的な文字列フォーマットとして次の 2 つがよく使用されます。</p>



<ol class="wp-block-list jinr-list">
<li><span class="jinr-d--text-color d--marker1 d--bold">f-string</span> を用いた方法</li>



<li><span class="jinr-d--text-color d--marker1 d--bold"><code>format</code></span> メソッドを用いた方法</li>
</ol>



<p class="wp-block-paragraph">f-string は Python 3.6 で導入された比較的新しい方法のため、それ以前のバージョンでは、<code>format</code> を使用する必要があります。</p>



<p class="wp-block-paragraph">一般的に f-string は format より高速で読みやすく、Pythonic な書き方とされているため、Python 3.6 以降では f-string の利用が推奨されます。とはいえ、最終的な選択は、開発者やプロジェクトのコーディングスタイルに依存します。</p>



<p class="wp-block-paragraph">この記事では、それぞれの方法で<span class="jinr-d--text-color d--marker1 d--bold">文字列をフォーマットする方法</span>について紹介します。</p>



<h3 class="wp-block-heading jinr-heading d--bold">f-string を用いて文字列をフォーマットする方法</h3>



<p class="wp-block-paragraph">文字列をフォーマットする際には、<span class="jinr-d--text-color d--marker1 d--bold">f-string</span> を使用します。日本語では「フォーマット済み文字列リテラル」といいます。</p>



<p class="wp-block-paragraph">なお、f-string は、<span class="jinr-d--text-color d--marker1 d--bold">Python 3.6</span> で追加されているため、それ以前のバージョンでは後述する <code>format</code> を使用してください。</p>



<h4 class="wp-block-heading jinr-heading d--bold" id="フォーマット文字列の一般的な使い方">基本的な使い方</h4>



<p class="wp-block-paragraph">f-string は、文字列の前に接頭辞 <code>f</code> または <code>F</code> が付与されている文字列です。f-string では <code>{}</code> で区切られた置換フィールドに変数や式を直接指定できます。</p>



<p class="wp-block-paragraph">f-string の使い方を以下の例で見てみましょう。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># フォーマット文字列の使い方
name = '太郎'
sex = '男性'
age = 20

# f-stringで値を埋め込む
print(f'{name}は{age}歳の{sex}です。')
print(f'{name}は{age*2}歳の{sex}です。')</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
太郎は20歳の男性です。
太郎は40歳の男性です。</pre>



<p class="wp-block-paragraph"><code>f</code> を文字列の前につけ、文字列中で変数を埋め込みたい部分に <code>{}</code> を記載して埋め込む変数や式を指定します。<code>{}</code> 内には式も設定できるため、例での <code>{age*2}</code> のように指定することも可能です。</p>



<p class="wp-block-paragraph">f-string は値を埋め込むだけではなく、式を直接記述できる点が非常に強力で、どのような変数や式が埋め込まれるかが一目で分かります。</p>



<h4 class="wp-block-heading jinr-heading d--bold" id="フォーマット文字列で変数そのものを表示する方法-python-3-8で追加">変数や式を含めて表示する方法 </h4>



<p class="wp-block-paragraph"><span class="jinr-d--text-color d--marker1 d--bold">Python 3.8</span> 以降で変数に「<code>=</code>」をつける方法が追加されました。これにより出力文字列に変数を含めて表示できます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># フォーマット文字列で変数や式を表示する方法
name = '太郎'
sex = '男性'
age = 20

# f-stringで変数や式を含めて表示する方法
print(f'{name=}は{age=}歳の{sex=}です。')
print(f'{name=}は{age*2=}歳の{sex=}です。')</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
name='太郎'はage=20歳のsex='男性'です。
name='太郎'はage*2=40歳のsex='男性'です。</pre>



<p class="wp-block-paragraph">例では、f-string に <code>{age=}</code> や <code>{sex=}</code> と指定しています。結果には「age=20」「sex=&#8217;男性&#8217;」のような変数名と値のセットで表示できています。また、<code>{age*2=}</code> とすると「age*2=40」のように式を含めた表示ができます。</p>



<p class="wp-block-paragraph">計算結果のみでは、どういった式で計算されているか分かりにくいですが、この方法を使うとどのような式で計算されたのか一目で分かります。デバッグ時に使用すると特に便利です。</p>



<h3 class="wp-block-heading jinr-heading d--bold">formatを用いて文字列をフォーマットする方法</h3>



<p class="wp-block-paragraph">f-string 以前の Python から使われてきた代表的な文字列フォーマットの方法が <span class="jinr-d--text-color d--marker1 d--bold"><code>format</code></span> メソッドです。</p>



<h4 class="wp-block-heading jinr-heading d--bold" id="先頭から引数の値を順に埋め込む場合">先頭から引数の値を順に埋め込む場合</h4>



<p class="wp-block-paragraph"><code>format</code> メソッドの基本的な使い方は以下のようになります。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 先頭から引数の値を順に埋め込む
print('{}の性別は{}で、年齢は{}歳です。'.format('太郎', '男性', 20))

# 変数に値を入れて使用する場合も同様
name = '太郎'
sex = '男性'
age = 20
print('{}の性別は{}で、年齢は{}歳です。'.format(name, sex, age))</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
太郎の性別は男性で、年齢は20歳です。
太郎の性別は男性で、年齢は20歳です。</pre>



<p class="wp-block-paragraph">文字列内で値を埋め込みたい部分に <code>{}</code> を設定します。当該文字列の <code>format</code> メソッドの引数に値を指定すると、引数の順に先頭から値が <code>{}</code> の部分に埋め込まれます。</p>



<p class="wp-block-paragraph">この方法は、<code>format</code> メソッドにおける最も基本的な使い方ですが、文字列内の値の順番を変えたい場合、引数の順番も書き換える必要があり少し不便です。</p>



<p class="wp-block-paragraph">順番を入れ替えることを考慮した場合は、次に紹介する引数番号を指定した値を埋め込み方法が使用できます。</p>



<h4 class="wp-block-heading jinr-heading d--bold" id="引数の番号を指定して値を埋め込む場合">引数の番号を指定して値を埋め込む場合</h4>



<p class="wp-block-paragraph"><code>format</code> メソッドで、引数番号を指定して値を埋め込むには以下のようにします。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 引数の番号を指定して値を埋め込む
print('{0}は{2}歳の{1}です。'.format('太郎', '男性', 20))

# 変数に値を入れて使用する場合も同様
name = '太郎'
sex = '男性'
age = 20
print('{0}は{2}歳の{1}です。'.format(name, sex, age))</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
太郎は20歳の男性です。
太郎は20歳の男性です。</pre>



<p class="wp-block-paragraph">引数番号を指定する場合には、文字列中の <code>{}</code> 内に引数番号を指定します。</p>



<p class="wp-block-paragraph">このように指定しておくことで、1 度引数に指定した値の順番を変えたい場合には、文字列の <code>{}</code> 内の数字の順番を変更するのみで済みます。引数の番号は <code>0</code> からである点に注意しましょう。</p>



<p class="wp-block-paragraph">ただし、番号を使う場合もどの部分が何の情報化が分かりにくいという点があります。次に紹介する引数に名前を付ける方法を使うとよりプログラムが読みやすくなります。</p>



<h4 class="wp-block-heading jinr-heading d--bold" id="引数を名前付けして値を埋め込む場合">引数に名前をつけて値を埋め込む場合</h4>



<p class="wp-block-paragraph">format メソッドで、引数に名前を付けて値を埋め込むには以下のようにします。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 引数を名前付けして値を埋め込む
print('{name}は{age}歳の{sex}です。'.format(name='太郎', sex='男性', age=20))

# 変数に値を入れて使用する場合も同様
name1 = '太郎'
sex1 = '男性'
age1 = 20
print('{name}は{age}歳の{sex}です。'.format(name=name1, sex=sex1, age=age1))</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
太郎は20歳の男性です。
太郎は20歳の男性です。</pre>



<p class="wp-block-paragraph">引数に名前付けする場合には、文字列中の <code>{}</code> 内に引数名を指定します。</p>



<p class="wp-block-paragraph"><code>format</code> メソッドの引数にはキーワード引数の形式で変数と値を指定します。このように引数に名前を付けて埋め込みを行うことで、文字列中のどの部分にどういった情報が埋め込まれるのか分かりやすくなります。</p>



<h3 class="wp-block-heading jinr-heading d--bold">書式設定をする方法</h3>



<p class="wp-block-paragraph">上記で紹介した f-string や <code>format</code> では、<code>{}</code> 内に「<code>:</code> (コロン)」を使って書式指定をすることで表示形式を変更することができます。</p>



<p class="wp-block-paragraph">以降の例を見ると分かりますが、f-string の場合は <code>{val:xxx}</code> (ここで <code>val</code> は変数や式)、<code>format</code> の場合は <code>{:xxx}</code> のように書式を指定します。</p>



<p class="wp-block-paragraph">以降で、代表的な書式設定方法について紹介します。</p>



<h4 class="wp-block-heading jinr-heading d--bold">左寄せ、中央寄せ、右寄せで表示する</h4>



<p class="wp-block-paragraph">左寄せ、中央寄せ、右寄せで表示したい場合には、以下のように「<code>&lt;</code>」(左寄せ)、「<code>^</code>」(中央寄せ), 「<code>></code>」(右寄せ)を使用して、表示桁数を指定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = 100

print("----- 左寄せ")
print("format  : {:&lt;10}".format(num))
print(f"f-string: {num:&lt;10}")

print("----- 中央寄せ")
print("format  : {:^10}".format(num))
print(f"f-string: {num:^10}")

print("----- 右寄せ")
print("format  : {:>10}".format(num))
print(f"f-string: {num:>10}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
format  : 100       
f-string: 100       
----- 中央寄せ
format  :    100    
f-string:    100    
----- 右寄せ
format  :        100
f-string:        100</pre>



<p class="wp-block-paragraph">例では、数値 <code>100</code> の表示に <code>10</code> 桁を使用し、左寄せ、中央寄せ、右寄せで表示しています。<code>:</code>　に続けて「<code>&lt;</code>」「<code>^</code>」「<code>></code>」で表示位置指定し、続けて桁数を記載します。</p>



<p class="wp-block-paragraph">表示の際に、数値以外の部分はスペースで補完されます。</p>



<h4 class="wp-block-heading jinr-heading d--bold">左寄せ、中央寄せ、右寄せで表示する（補完する文字の指定）</h4>



<p class="wp-block-paragraph">左寄せ、中央寄せ、右寄せで表示する際に、補完する文字を指定する場合には以下のように補完する文字を指定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = 100

print("----- 左寄せ")
print("format  : {:*&lt;10}".format(num))
print(f"f-string: {num:*&lt;10}")

print("----- 中央寄せ")
print("format  : {:*^10}".format(num))
print(f"f-string: {num:*^10}")

print("----- 右寄せ")
print("format  : {:*>10}".format(num))
print(f"f-string: {num:*>10}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- 左寄せ
format  : 100*******
f-string: 100*******
----- 中央寄せ
format  : ***100****
f-string: ***100****
----- 右寄せ
format  : *******100
f-string: *******100</pre>



<p class="wp-block-paragraph">例では、補完する文字に「<code>*</code>」を指定しています。このようにすると左寄せ、中央寄せ、右寄せになっていることがより分かりやすくなります。</p>



<h4 class="wp-block-heading jinr-heading d--bold">符号を表示する</h4>



<p class="wp-block-paragraph">通常は数値のプラス符号は表示されませんが、以下のように <code>:</code> に続けて「<code>+</code>」を指定することでプラスの値に符号をつけることができます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num1 = 100
num2 = -100

print("----- 符号(プラスを表示)")
print("format  : {:+}".format(num1))
print(f"f-string: {num1:+}")
print("format  : {:+}".format(num2))
print(f"f-string: {num2:+}")

print("----- 符号 (スペースで符号位置を揃える)")
print("format  : {: }".format(num1))
print(f"f-string: {num1: }")
print("format  : {: }".format(num2))
print(f"f-string: {num2: }")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- 符号(プラスを表示)
format  : +100
f-string: +100
format  : -100
f-string: -100
----- 符号 (スペースで符号位置を揃える)
format  :  100
f-string:  100
format  : -100
f-string: -100</pre>



<p class="wp-block-paragraph">例のようにプラスの符号が表示できることが分かります。また、<code>:</code> の後ろにスペースを入れると <code>+</code> 符号の位置にスペースが入るため、数値の位置を揃えることができます。</p>



<h4 class="wp-block-heading jinr-heading d--bold">桁区切りを表示する</h4>



<p class="wp-block-paragraph">金額表示では 3 桁ごとの桁区切りのカンマ(<code>,</code>)をよく入れます。この桁区切りを指定するには以下のように <code>:</code> に続けて「<code>,</code>」を指定します。また、<span class="jinr-d--text-color d--marker1 d--bold">Python 3.6</span> で、アンダーバー(<code>_</code>)での桁区切りも追加されています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = 1000000.123456

print("----- 桁区切りの表示 (カンマ ,)")
print("format  : {:,}".format(num))
print(f"f-string: {num:,}")

print("----- 桁区切りの表示 (アンダーバー _) ※Python3.6で追加")
print("format  : {:_}".format(num))
print(f"f-string: {num:_}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- 桁区切りの表示 (カンマ ,)
format  : 1,000,000.123456
f-string: 1,000,000.123456
----- 桁区切りの表示 (アンダーバー _) ※Python3.6で追加
format  : 1_000_000.123456
f-string: 1_000_000.123456</pre>



<p class="wp-block-paragraph">例のように桁区切りで表示すると数値がより見やすくなります。</p>



<h4 class="wp-block-heading jinr-heading d--bold">ゼロ埋めで表示する</h4>



<p class="wp-block-paragraph">数値をゼロ埋めで表示する場合には、以下のように <code>:</code> に続けて <code>0=</code> を記載し、その後に桁数を指定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print("----- ゼロ埋め (正の数)")
num = 100
print("format  : {:0=10}".format(num))
print(f"f-string: {num:0=10}")
# ゼロ埋めの場合=は省略可能
print("format  : {:010}".format(num))
print(f"f-string: {num:010}")

print("----- ゼロ埋め (負の数)")
num = -100
print("format  : {:0=10}".format(num))
print(f"f-string: {num:0=10}")
# ゼロ埋めの場合=は省略可能
print("format  : {:010}".format(num))
print(f"f-string: {num:010}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- ゼロ埋め (正の数)
format  : 0000000100
f-string: 0000000100
format  : 0000000100
f-string: 0000000100
----- ゼロ埋め (負の数)
format  : -000000100
f-string: -000000100
format  : -000000100
f-string: -000000100</pre>



<p class="wp-block-paragraph">数値がゼロ埋めされることが分かります。なお、上記例でも使っているように、ゼロ埋めの場合は「<code>=</code>」は省略して {<code>:010</code>} というような記載もできます。</p>



<p class="wp-block-paragraph">また、マイナスの値の場合は符号が表示されてからゼロ埋めの数値が表示されます。</p>



<h4 class="wp-block-heading jinr-heading d--bold">2 進数、8 進数、16 進数で表示する</h4>



<p class="wp-block-paragraph">2 進数で表示する場合は「<code>b</code>」、8 進数で表示する場合は「<code>o</code>」、16 進数で表示する場合は「<code>x</code>」または「<code>X</code>」を <code>:</code> に続けて記載します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = 255

print("----- 2進数表記")
print("format  : {:b}".format(num))
print(f"f-string: {num:b}")

print("----- 8進数表記")
print("format  : {:o}".format(num))
print(f"f-string: {num:o}")

print("----- 16進数表記 (小文字)")
print("format  : {:x}".format(num))
print(f"f-string: {num:x}")

print("----- 16進数表記 (大文字)")
print("format  : {:X}".format(num))
print(f"f-string: {num:X}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- 2進数表記
format  : 11111111
f-string: 11111111
----- 8進数表記
format  : 377
f-string: 377
----- 16進数表記 (小文字)
format  : ff
f-string: ff
----- 16進数表記 (大文字)
format  : FF
f-string: FF</pre>



<p class="wp-block-paragraph">2 進数、8 進数、16 進数で表示できていることが分かります。なお、16進数については、小文字の「<code>x</code>」の場合は小文字、大文字の「<code>X</code>」の場合は大文字の表示になります。</p>



<h4 class="wp-block-heading jinr-heading d--bold">2 進数、8 進数、16 進数で表示する（ゼロ埋め）</h4>



<p class="wp-block-paragraph">2 進数、8 進数、16 進数での表示でゼロ埋め表示したい場合は、上記で紹介したゼロ埋めと組み合わせることができます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = 255

print("----- 2進数表記")
print("format  : {:0=10b}".format(num))
print(f"f-string: {num:0=10b}")

print("----- 8進数表記")
print("format  : {:0=10o}".format(num))
print(f"f-string: {num:0=10o}")

print("----- 16進数表記 (小文字)")
print("format  : {:0=10x}".format(num))
print(f"f-string: {num:0=10x}")

print("----- 16進数表記 (大文字)")
print("format  : {:0=10X}".format(num))
print(f"f-string: {num:0=10X}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- 2進数表記
format  : 0011111111
f-string: 0011111111
----- 8進数表記
format  : 0000000377
f-string: 0000000377
----- 16進数表記 (小文字)
format  : 00000000ff
f-string: 00000000ff
----- 16進数表記 (大文字)
format  : 00000000FF
f-string: 00000000FF</pre>



<h4 class="wp-block-heading jinr-heading d--bold">小数点以下の桁数を指定して表示する</h4>



<p class="wp-block-paragraph">小数点以下の桁数を指定したい場合は、<code>:</code> の後で「<code>.桁数f</code>」とすることで小数点以下の桁数を指定できます。なお、「<code>f</code>」については大文字の「<code>F</code>」でも構いません。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = 0.00000123456

print("----- 値によって自動で指数表記となる")
print("format  : {}".format(num))
print(f"f-string: {num}")

print("----- 固定小数点表記で表示 (デフォルトは小数点以下6桁)")
print("format  : {:f}".format(num))
print(f"f-string: {num:f}")

print("----- 小数点以下の桁数指定 (桁数を指定)")
print("format  : {:.15f}".format(num))
print(f"f-string: {num:.15f}")

num1 = 0.0014
num2 = 0.0015
num3 = 0.0016
print("----- 固定小数点表記で表示 (四捨五入)")
print("format  : {:.3f}".format(num1))
print(f"f-string: {num1:.3f}")
print("format  : {:.3f}".format(num2))
print(f"f-string: {num2:.3f}")
print("format  : {:.3f}".format(num3))
print(f"f-string: {num3:.3f}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- 値によって自動で指数表記となる
format  : 1.23456e-06
f-string: 1.23456e-06
----- 固定小数点表記で表示 (デフォルトは小数点以下6桁)
format  : 0.000001
f-string: 0.000001
----- 小数点以下の桁数指定 (桁数を指定)
format  : 0.000001234560000
f-string: 0.000001234560000
----- 固定小数点表記で表示 (四捨五入)
format  : 0.001
f-string: 0.001
format  : 0.002
f-string: 0.002
format  : 0.002
f-string: 0.002</pre>



<p class="wp-block-paragraph">例のように、フォーマットでは何も指定しない場合、数値の大きさによって自動的に指数表記になります。「<code>f</code>」または「<code>F</code>」を用いることで固定小数点の表示になります。</p>



<p class="wp-block-paragraph">桁数を指定しない場合は、小数点以下 6 桁がデフォルトです。上記例で桁数を指定することで小数点以下の桁数を変えられることが分かります。また、桁数で表示しきれない部分は四捨五入になっていることが分かります。</p>



<h4 class="wp-block-heading jinr-heading d--bold">指数表記で表示する</h4>



<p class="wp-block-paragraph">指数表記で表示したい場合には、<code>:</code> に続けて「<code>e</code>」または「<code>E</code>」を指定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num1 = 0.0000123456
num2 = 123456

print("----- 指数表記 (デフォルトは小数点以下6桁)")
print("format  : {:e}".format(num1))
print(f"f-string: {num1:e}")
print("format  : {:e}".format(num2))
print(f"f-string: {num2:e}")

print("----- 小数点以下の桁数を指定")
print("format  : {:.3e}".format(num1))
print(f"f-string: {num1:.3e}")
print("format  : {:.3e}".format(num2))
print(f"f-string: {num2:.3e}")

print("----- Eとすると表記が大文字になる")
print("format  : {:.3E}".format(num1))
print(f"f-string: {num1:.3E}")
print("format  : {:.3E}".format(num2))
print(f"f-string: {num2:.3E}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- 指数表記 (デフォルトは小数点以下6桁)
format  : 1.234560e-05
f-string: 1.234560e-05
format  : 1.234560e+05
f-string: 1.234560e+05
----- 小数点以下の桁数を指定
format  : 1.235e-05
f-string: 1.235e-05
format  : 1.235e+05
f-string: 1.235e+05
----- Eとすると表記が大文字になる
format  : 1.235E-05
f-string: 1.235E-05
format  : 1.235E+05
f-string: 1.235E+05</pre>



<p class="wp-block-paragraph">上記例では指数表記で表示できていることが分かります。なお、指数部分の <code>e</code> の表記は指定した「<code>e</code>」「<code>E</code>」にあわせて小文字、大文字が変わります。</p>



<h4 class="wp-block-heading jinr-heading d--bold">パーセント表示する %</h4>



<p class="wp-block-paragraph">数値をパーセント表記したい場合は、<code>:</code> に続けて「<code>%</code>」を指定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = 0.15

print("----- パーセント表記(%)")
print("format  : {:%}".format(num))
print(f"f-string: {num:%}")

print("----- 小数点以下の桁数を指定")
print("format  : {:.2%}".format(num))
print(f"f-string: {num:.2%}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- パーセント表記(%)
format  : 15.000000%
f-string: 15.000000%
----- 小数点以下の桁数を指定
format  : 15.00%
f-string: 15.00%</pre>



<p class="wp-block-paragraph">デフォルトでは小数点以下が 6 桁になっているため、上記の小数点以下表記の記載方法を使って「<code>.桁数%</code>」とすることで小数点以下の桁数を指定することが可能です。</p>



<h4 class="wp-block-heading jinr-heading d--bold">日付表示する datetime</h4>



<p class="wp-block-paragraph">日付表示をする場合には、<code>datetime</code>モジュールを使って生成した値をフォーマットで渡すだけで表示できます。その際に <code>:</code> に続けて日付フォーマット文字列を指定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import datetime

dt = datetime.datetime(2023, 1, 2, 12, 30, 30)

print("----- 日付の表示")
print("format  : {}".format(dt))
print(f"f-string: {dt}")

print("-----日付フォーマットの指定")
print("format  : {:%Y/%m/%d %I:%M:%S, %A, %p}".format(dt))
print(f"f-string: {dt:%Y/%m/%d %I:%M:%S, %A, %p}")

print("----- ISOフォーマットでの表示")
print("format  : {}".format(dt.isoformat()))
print(f"f-string: {dt.isoformat()}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
----- 日付の表示
format  : 2023-01-02 12:30:30
f-string: 2023-01-02 12:30:30
-----日付フォーマットの指定
format  : 2023/01/02 12:30:30, Monday, PM
f-string: 2023/01/02 12:30:30, Monday, PM
----- ISOフォーマットでの表示
format  : 2023-01-02T12:30:30
f-string: 2023-01-02T12:30:30</pre>



<p class="wp-block-paragraph">日時のフォーマットを指定する場合には上記のような「<code>%Y</code>」といった書式コードを使用します。日時の書式コードについては、公式ドキュメントの<a href="https://docs.python.org/ja/3/library/datetime.html#strftime-and-strptime-format-codes" target="_blank" rel="noreferrer noopener">書式コード一覧</a>に記載があるのでこちらを参考にして変更してみてください。</p>



<p class="wp-block-paragraph">また、ISOフォーマットであれば <code>isoformat</code> メソッドで生成した文字列を表示した方が早いです。なお、<code>datetime</code> モジュールで日付や時刻を整形する方法については「<a href="https://tech.nkhn37.net/python-datetime-strftime-setlocale/" target="_blank" rel="noreferrer noopener">日付や時刻を整形する方法</a>」を参考にしてください。</p>



<h2 class="wp-block-heading jinr-heading d--bold">まとめ</h2>



<p class="wp-block-paragraph">Python で<span class="jinr-d--text-color d--marker1 d--bold">文字列をフォーマットする方法</span>を解説しました。</p>



<p class="wp-block-paragraph">Python で代表的な以下文字列フォーマットの使い方を紹介しています。</p>



<ol class="wp-block-list jinr-list">
<li><span class="jinr-d--text-color d--marker1 d--bold">f-string</span> を用いた方法</li>



<li><span class="jinr-d--text-color d--marker1 d--bold"><code>format</code></span> メソッドを用いた方法</li>
</ol>



<p class="wp-block-paragraph">プログラム中に <code>print</code> で値を埋め込んだ文字列を表示することは頻繁に行います。また、他にもログファイルのフォーマットの場面でも同様に必要な場合があります。ぜひ、文字列のフォーマット方法の基本を押さえてもらいたいと思います。</p>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>


<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box8  "><div class="a--simple-box-title d--bold">ソースコード</div><div class="c--simple-box-inner">
<p class="wp-block-paragraph">上記で紹介しているソースコードについては <a href="https://github.com/nkhn37/python-tech-sample-source/tree/main/python-basic/string/format" target="_blank" rel="noreferrer noopener">GitHub</a> にて公開しています。参考にしていただければと思います</p>
</div></div></section>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/python-str-format-f-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-06-14 21:55:28 by W3 Total Cache
-->