2017-05-08 9 views
3

Pythonの文字列形式のコロンの意味は何ですか? Pythonの<a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow noreferrer">Format Specification Mini-Language</a>の読書で

format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] 
fill  ::= <any character> 
align  ::= "<" | ">" | "=" | "^" 
sign  ::= "+" | "-" | " " 
width  ::= integer 
precision ::= integer 
type  ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" 

文法は本当に私を混乱しました。私はバイナリ表現 にint型を変換したい場合は

例えば、私が行うことができます。この

"{0:b}".format(100) 
"{:b}".format(100) # but this is fine too, so what dose the 0 do? 

私はb仕様でtype一部を表していることを知っているが、私はの役割を把握することはできません0:、彼らは何をしていますか?あなたが唯一のformat_specのための文法を見ている

+0

https://pyformat.info/を参照してください。 – bigbounty

答えて

3

、完全な文法はhigher up on the same pageが指定されている:format_specの前replacement_field構文通知:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}" 
field_name  ::= arg_name ("." attribute_name | "[" element_index "]")* 
arg_name   ::= [identifier | integer] 
attribute_name ::= identifier 
element_index  ::= integer | index_string 
index_string  ::= <any source character except "]"> + 
conversion  ::= "r" | "s" 
format_spec  ::= <described in the next section> 

field_nameはコロンに先行 あるformat_spec、感嘆符'!'が先行 ある変換フィールド、続いて必要に応じてであり、そして':'

場合field_nameと/またはconversionが指定されている場合、:は、前者の末尾とformat_specの先頭を示します。あなたの例で

>>> "{0:b}".format(100) 
'1100100' 

ゼロこの場合、渡されたパラメータタプルでフォーマットする項目のインデックスに対応する任意field_nameを指定します。それは省略可能なので、削除することができます。

関連する問題