python:language_memo

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

両方とも前のリビジョン 前のリビジョン
次のリビジョン
前のリビジョン
python:language_memo [2011/06/19 10:25] ともやんpython:language_memo [2019/08/19 07:01] (現在) ともやん
行 1: 行 1:
 ====== Python ランゲージ メモ ====== ====== Python ランゲージ メモ ======
 +
 ===== 文字列 ===== ===== 文字列 =====
 +
 ==== 書式編集 ==== ==== 書式編集 ====
 <code python> <code python>
 str = 'integer value: %d' % int_val str = 'integer value: %d' % int_val
 str = "string value: '%s' integer value: %d" % (str_val, int_val) str = "string value: '%s' integer value: %d" % (str_val, int_val)
 +str = "dic['key']: '%(key)s'" % { 'key' : 'abc' }
 +
 +"string value: '{}' integer value: {}".format('abc', 123)
 +"string value: 'abc' integer value: 123"
 +
 +str_val = 'abc'
 +int_val = 123
 +f"string value: '{str_val}' integer value: {int_val}"
 +"string value: 'abc' integer value: 123"
 +
 +int_val = 123456789
 +int_val1 = 12345
 +f'integer value: {int_val:,} integer value1: {int_val1:,}'
 +'integer value: 123,456,789 integer value1: 12,345'
 +
 +pi = 3.14159265358979
 +f'pi: {pi:.2f}'
 +'pi: 3.14'
 +
 +flt_val = 123456789.0123456
 +f'float value: {flt_val:,.4f}'
 +'float value: 123,456,789.0123'
 +
 +flt_val = 1234.5678
 +f'float value: {flt_val:>10,.2f}'
 +'float value:   1,234.57'
 +
 +'int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}'.format(65536)
 +'int: 65536; hex: 0x10000; oct: 0o200000; bin: 0b10000000000000000'
 </code> </code>
  
行 46: 行 77:
  文字列を日付型へ変換するには、以下のように記述する。  文字列を日付型へ変換するには、以下のように記述する。
 <code python> <code python>
 +import datetime
 +import time
 +
 datetime.date(*time.strptime('2009/05/23', '%Y/%m/%d')[:3]) datetime.date(*time.strptime('2009/05/23', '%Y/%m/%d')[:3])
 +datetime.date(2009, 5, 23)
 +
 datetime.datetime(*time.strptime('2009/05/23 17:16:12', '%Y/%m/%d %H:%M:%S')[:6]) datetime.datetime(*time.strptime('2009/05/23 17:16:12', '%Y/%m/%d %H:%M:%S')[:6])
 +datetime.datetime(2009, 5, 23, 17, 16, 12)
 +
 </code> </code>
  上記のコードは、以下のように動作している。  上記のコードは、以下のように動作している。
行 64: 行 102:
   - struct_time をスライス。   - struct_time をスライス。
   - 年月日のタプルに * を付けて、位置指定型の引数として datetime.date に渡す。   - 年月日のタプルに * を付けて、位置指定型の引数として datetime.date に渡す。
 +
 +===== クラス =====
 +<code python>
 +>>> class ClsA(object):
 +>>>     def method(self, arg1):
 +>>>         print("ClsA.method: %(arg1)s" % {"arg1" : arg1})
 +>>>
 +>>> class ClsB(ClsA):
 +>>>     def method(self, arg1):
 +>>>         print(super(ClsB, self))
 +>>>         super(ClsB, self).method(arg1)
 +>>>         print("ClsB.method: %(arg1)s" % {"arg1" : arg1})
 +>>>
 +>>> cls.method("test")
 +<super: <class 'ClsB'>, <ClsB object>>
 +ClsA.method: test
 +ClsB.method: test
 +</code>
 +
 +===== 参考文献 =====
 +[[https://note.nkmk.me/python-format-zero-hex/|Python, formatで書式変換(0埋め、指数表記、16進数など) | note.nkmk.me]]\\
 +[[https://qiita.com/mas9612/items/af6a3030f9ef19feae22|Python3のstr.format()メソッドのいろんな書式指定]]\\
  
  • python/language_memo.1308446731.txt.gz
  • 最終更新: 2019/05/18 02:23
  • (外部編集)