0
0

【Python】stringの扱いについて

Last updated at Posted at 2024-08-10

はじめに

Pythonのstrのformatメソッドについて記載したいと思います。
Pythonのソースコードは直感的に利用できます。文字列連結については単純に+演算子で連結可能ですが連結回数が多いほど可読性は低くなります。
一方でformatメソッドを利用することで、文字列連結は不要となるため、可読性が向上します。

Python基本構文については【Python入門】基礎構文のまとめでまとめてますので、参考にしてください。

stringの操作

stringモジュールのformatメソッドを用いることで独自の文字列フォーマットとしてカスタマイズ可能となります。

ポジション指定

ポジション指定のフォーマット例になります。
{0}と記載することで、第1引数を参照します。
{}と記載することで位置引数指定を省略可能となります。
"{0} {1}"は"{} {}"と同じ意味になります。

    # ポジション指定
    print("1:{0}".format("first"))
    print("2:{}".format("first"))
    print("3:{} {}".format("first","second"))
    print("4:{0} {1}".format("first","second"))

keyword指定

keywordを指定のフォーマット例になります。
playersの例は配列要素へのアクセス例となります。

    # keyword指定
    print("5:{name}".format(name="name0"))
    print("6:0.{weight}".format(weight=100))
    print("7:{players[0]}".format(players=["name1", "name2", "name3"]))

変換

str,repr,asciiへの変換例になります。
__str__、__repr__等の組み込み関数を利用することも可能となります。
3つ目の例については非ascii文字は\uでエスケープします

    # 変換
    print("8:test {0!s}".format(Person("name", 20)))
    print("9:test {!r}".format(Person("name", 20)))
    print("10:test {0!a}".format("テスト"))

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self) -> str:
        return "Str Person(name={0}, age={1})".format(self.name, self.age)

    def __repr__(self) -> str:
        return "Repr Person(name={0}, age={1})".format(self.name, self.age)

要素へのアクセス

配列の要素指定のフォーマット例となります。

    # 要素へのアクセス
    element = (1, 2, 3)
    print("11:{0[0]}".format(element))

定数

#をつけることで、プレフィック付き指定のフォーマット例となります。

    # 定数の指定(プレフィックスなし)
    print("12:int:{0},hex:{0:x},bin:{0:b}".format(100))
    # 定数の指定(プレフィックス付き)
    print("13:int:{0},hex:{0:#x},bin:{0:#b}".format(100))

数字のセパレーター

カンマをつけることで数字のセパレーター付き指定のフォーマット例となります。

    # 数字のセパレーター
    print("14:{0:,}".format(1000000))

時刻変換

時刻の書式指定のフォーマット例となります。

    # 時刻の変換
    d = datetime.datetime(2019, 1, 2, 23, 5, 8)
    print("15:{:%Y-%m-%d %H:%M:%S}".format(d))

まとめ

string操作についてはコーディング規約には記載しないことが多いため、既存ソースを参照して作成することが多くなると思います。参照したソースがコードレビューを終えている場合、問題ない操作方法と判断されると思います。
単純な文字列連結については問題ないですが、少し複雑なstring操作を行う場合はformatを利用してみてください。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0