Python
1>>> class Hoge:
2... def __getitem__(self, arg):
3... print(type(arg), arg)
4...
5>>> '{0[:2]}'.format(Hoge())
6<class 'str'> :2
7'None'
スライスオブジェクトではなく、文字列:2
が渡ってしまっています。
解決するには、Python3.6以降で導入されたf-stringを使うのが良いのではないでしょうか。
Python
1>>> word = 'highschool'
2>>> f'{word}は{word[:4]}と{word[4:]}でできています。'
3'highschoolはhighとschoolでできています。'
追記
ドキュメントに次のような記述がありました。
置換フィールドの文法は以下です:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | digit+]
attribute_name ::= identifier
element_index ::= digit+ | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= <described in the next section>
引用元: Python 標準ライブラリ » string » 書式指定文字列の文法
element_indexとしてスライスオブジェクトが認められていないようですね。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/06 13:20