PythonのString Formattingを拡張

Python 3で追加されたformatを使うと文字列操作が便利になります。

使い方は次のような感じです。(参考:Pythonの新しい文字列書式操作

>>> '{0} + {1} = {2}'.format(1, 2, 1+2)
'1 + 2 = 3'

string.Formatterを継承すると、この文字列操作を拡張することができるそうです。

拡張の仕方は以下のような感じです。

class Formatter(string.Formatter):
  def format_field(self, value, spec):
    # 必要な処理
    return 'value'

サンプル

このstring.Formatterを継承してupperlowerを書式指定文字列に使うと大文字・小文字に変換するサンプルを作ってみました。

import string
class Formatter(string.Formatter):
  def format_field(self, value, spec):
    if spec == 'upper': value, spec = value.upper(), ''
    elif spec == 'lower': value, spec = value.lower(), ''
    return super(Formatter, self).format_field(value, spec)

使い方は以下のような感じです。

>>> f = Formatter()
>>> f.format('{name} {name:upper} {name:lower}', name='Alice')
'Alice ALICE alice'

template engine

このString Formattingを使ってtemplate engineのようなことを実装したサンプルのようなものも公開されているみたいです。

GitHub – ebrehault/superformatter
https://github.com/ebrehault/superformatter

repeatcallifに対応していて、次のような感じで使えます。

>>> from engine import SuperFormatter
>>> sf = SuperFormatter()
>>> print(sf.format('{n:repeat:n={{item}}\n}', n=[2,3,5,7]))
n=2
n=3
n=5
n=7

現状ではサンプル程度のものかと思いますが、面白そうなテクニックかなと思います。

リンク

string — Common string operations — Python 3.7.2 documentation
https://docs.python.org/3/library/string.html

The world’s simplest Python template engine — Makina Corpus
https://makina-corpus.com/blog/metier/2016/the-worlds-simplest-python-template-engine

関連記事

Pythonでnkf
Pythonで文字コードが不明な文字列(例えばインターネット上のHTMLは文字コードが間違っている場合があります)はnkfを使うと簡単に取り扱うことができるみたいです。 # emerge -pv app-i18n/nkf These are the packages that would be merged, in order: Calculating dependencies... ...

python-chardet
python-chardetを使った文字コード推定 使い方 >>> import chardet >>> s = 'こんにちは' >>> chardet.detect(s) {'confidence': 0.9690625, 'encoding': 'utf-8'} >>> s.decode(chardet.detect(s)['encoding']) u'\u3053\u3...

Pythonの新しい文字列書式操作
Pythonのformatを使った新しい文字列の書式操作注は、{}を使って次のようにして使います。 >>> '{0} + {1} = {2}'.format(1, 2, 1+2) '1 + 2 = 3' {0} {1} {2}が順になっている場合はポジション引数は省略可能です。 >>> '{} + {} = {}'.format(1, 2, 1+2) '1 + 2 = 3' ...

PythonでUnicodeのオブジェクトとコードポイントの変換
UnicodeオブジェクトをUnicodeコードポイントに変換 >>> ord(u'あ') 12354 UnicodeコードポイントをUnicodeオブジェクトに変換 >>> unichr(12354) u'\u3042' >>> print unichr(12354) あ 8ビット文字列にordを使うとASCIIコードを取得することもできます。 >>> ord('...

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です