python:language_memo

文書の過去の版を表示しています。


Python ランゲージ メモ

str = 'integer value: %d' % int_val
str = "string value: '%s' integer value: %d" % (str_val, int_val)
str = "dic['key']: '%(key)s'" % { 'key' : 'abc' }
str = str.replace("\r\n", "<br />")

 split は文字列を指定された区切り文字で分割しリストとして返却する。

>>> 'a,b,c,d,e'.split(',')
['a', 'b', 'c', 'd', 'e']
>>> 'a b c d e'.split()
['a', 'b', 'c', 'd', 'e']

 join は指定されたシーケンスを文字列で連結して返却する。

>>> ','.join(['a', 'b', 'c', 'd', 'e'])
'a,b,c,d,e'

 python で trim するには、strip、lstrip、rstrip を使う。これらは文字列の前後のスペースを除去した結果を返す。

>>> str = '    mojimoji   '
>>> str.strip()
'mojimoji'
>>> str.lstrip()
'mojimoji   '
>>> str.rstrip()
'    mojimoji'
>>> str
'    mojimoji   '

 文字列を日付型へ変換するには、以下のように記述する。

datetime.date(*time.strptime('2009/05/23', '%Y/%m/%d')[:3])
datetime.datetime(*time.strptime('2009/05/23 17:16:12', '%Y/%m/%d %H:%M:%S')[:6])

 上記のコードは、以下のように動作している。

>>> import datetime
>>> import time
>>> time.strptime('2009/05/23', '%Y/%m/%d')          
(2009, 5, 23, 0, 0, 0, 5, 143, -1)
>>> time.strptime('2009/05/23', '%Y/%m/%d')[:3]
(2009, 5, 23)
>>> datetime.date(*time.strptime('2009/05/23', '%Y/%m/%d')[:3])
datetime.date(2009, 5, 23)
>>> 
  1. time.strptime にて struct_time に変換。
  2. struct_time をスライス。
  3. 年月日のタプルに * を付けて、位置指定型の引数として datetime.date に渡す。
>>> 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
  • python/language_memo.1558113795.txt.gz
  • 最終更新: 2019/05/18 02:23
  • by 非ログインユーザー