format関数の具体的な用例をいくつか示します。
print('{}'.format(user))
-> abcde
print('user: {}'.format(user))
-> user: abcde
つまりformat関数には、文字列中の {}
を、format関数の引数に置き換える機能を持っています。
{}
の間の:
がどういう意味を持つのか
format関数が影響を及ぼすのは{}
のみであるため、:
は何にも影響しません。
…が、本来の目的のbasic認証とは大いに関係があります。
basic認証が設定されているページは、ブラウザのポップアップに入力する手段の他に、URLに直接記述を行うことでも認証を突破することができます。
例) http://user:password@www.hoge.com/
この例のようにユーザ名とパスワードを :
で区切る必要があるため、{}:{}
という書き方になっていると思われます。
(おそらく、プログラムの後半に 'https://{}@www.hoge.com'.format(basic_user_and_pasword)
のような記述があるのではないでしょうか?)
format関数の,
がどういう意味を持つのか
format関数が文字列中の {}
を変数に置き換えることができるのは、ひとつだけではありません。
format関数の引数に ,
を使うことでいくつも要素を追加することで、複数の {}
を置き換えることができます。
つまり,
とは、要素の区切りのことです。
たとえば
print('{}{}'.format('hello ', 'world!'))
-> hello world!
また、複数個の場合は前から順番の置き換えになります。
print('{}{}{}{}'.format('A', 'B', 'C', 'D'))
-> ABCD
発展させて、以下のようにも書くことができます。
print('I have a {}, I have an {}.'.format('pen', 'apple'))
-> I have a pen, I have an apple.
ちなみに{}
の数とformat関数の引数が同数でないときは、以下のようになります。
format関数の引数の方が多い場合
print('{}{}{}{}'.format('A', 'B', 'C', 'D', 'E'))
-> ABCD # 最後の'E'は無視される
{}
のほうが多い場合
print('{}{}{}{}'.format('A', 'B', 'C'))
-> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range # 引数が足りないというエラーになる
以上のことを踏まえると、{}:{}
は以下のような出力になることがわかります。
user = 'abcde'
password = '12345'
print('{}:{}'.format(user, password))
-> abcde:12345
蛇足ですが、すこし冗長ながら以下のように記述することもできます。
user = 'abcde'
password = '12345'
# 以下の3行が↓とおなじ
# basic_user_and_pasword = base64.b64encode('{}:{}'.format(user, password).encode('utf-8'))
user_and_password = '{}:{}'.format(user, password)
user_and_password_encoded = user_and_password.encode('utf-8')
user_and_password_b64 = base64.b64encode(user_and_password_encoded)