1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonのf-stringの!

Posted at

手短に

下記のような表示をしたかった。

a=1
b='hello'

文字列の時はクオーテーションマークをつけたいが、f"b={b}"だとうまく行かない。
こうすると良い。

print(f"b={b!r}")
# b='hello'

!以降はconversionを示す。

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>

field_name の後に、感嘆符 '!' を挟んで conversion フィールドを続けることができます。
現在 3つの変換フラグがサポートされています: 値に対して str() を呼ぶ '!s' 、 repr() を呼ぶ '!r' 、 ascii() を呼ぶ '!a'。

ソース

蛇足&感想

f"b={repr(b)}"でもよい。
知らなかった。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?