くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

PythonのMyチートシート(随時更新)

Pythonでよく調べなおすので、個人的なチートシート

map, filter

items = [1, 2, 3]
map(lambda n:n+20, items)
# => [21, 22, 23]

[x+20 for x in items] 
# => [21, 22, 23]


filter(lambda n:n%2==1, items)
# => [1, 3]

[x for x in items if x%2==1]
# => [1, 3]

ref: map, reduce, filterによるシーケンス操作 | Python Snippets

文字列

フォーマット

num =5
"{0}, {0:02d}".format(num)
#=> '5, 05'

ref: format関数による文字列フォーマット(新しい形式 / 3.6対応) | Python Snippets ref: 2. 字句解析 — Python 3.6.1 ドキュメント

文字列リストを連結

words = ['This', 'is', 'a', 'pen']
print ' '.join(words)
# => This is a pen

ref Pythonで文字列リストを連結 - 超言理論

URLエンコード

import urllib
import urlparse

# Encode
urllib.parse.quote("テスト")
# => %E3%83%86%E3%82%B9%E3%83%88

# Decode
urllib.parse.unquote("%E3%83%86%E3%82%B9%E3%83%88")
# => テスト

ref: PythonのURLとクエリパラメータのパースまとめ - Qiita

日付

要素の取得

import datetime
now = datetime.datetime.now()
now.year
now.month
now.day
now.hour
now.minute
now.second
now.microsecond
datetime.weekday()    # 月曜日を 0、日曜日を 6 として、曜日を整数で返す

date = now.date()     # date
time = now.time()     # TimeZoneなしのtime
timetz = now.timetz() # TimeZoneありのtime


# timedelta
delta = datetime.timedelta()
delta.days            # 日
delta.seconds         # 秒
delta.microseconds    # ミリ秒
delta.total_seconds() # この期間に含まれるトータルの秒数を返します。td / timedelta(seconds=1) と等価です。

ref 8.1. datetime — 基本的な日付型および時間型 — Python 3.6.1 ドキュメント

フォーマット

import datetime
now = datetime.datetime.now()
now.strftime("%Y/%m/%d %H:%M:%S")
# => '2012/01/01 20:29:39'
DIRECTIVE MEANING
%Y 上 2 桁付きの西暦年を表す 10 進数。
%m 月を表す 10 進数 [01,12]。
%d 月の始めから何日目かを表す 10 進数 [01,31]。
%H (24 時間計での) 時を表す 10 進数 [00,23]。
%M 分を表す 10 進数 [00,59]。
%S 秒を表す 10 進数 [00,61]。
%a ロケールにおける省略形の曜日名。
%b ロケールにおける省略形の月名。

ref 日付フォーマット(datetime⇔文字列) | Python Snippets

加算・減算

# $ pip install dateutils
import datetime
from dateutil.relativedelta import relativedelta
datetime.datetime(2016, 12, 1) + relativedelta(months=1)  #年をまたいだ1ヶ月加算
datetime.datetime(2017, 1, 1, 0, 0)

ref 日付に月単位で加算減算する (relativedelta) | Python Snippets

基本

例外

""" 例外ハンドリング"""
try:
  # [失敗して例外名1もしくは例外名2の例外を発生させる可能性のある処理(関数呼び出し)...]
except [例外名1] as [例外オブジェクト1]:
  # [例外名1の例外が発生した場合の処理...]
except [例外名2] as [例外オブジェクト2]:
  # [例外名2の例外が発生した場合の処理...]
# ...
else:
  # [いずれの例外も発生しなかった場合の処理...]

"""例外の発生"""
raise [例外名] ([引数...])


"""ユーザ定義例外"""
class MyException (Exception):
  def __str__ (self):                      # エラーメッセージ
    return ('MyException')

ref: Pythonの例外とその処理に関する覚え書き(ユーザ定義の例外など) - 試験運用中なLinux備忘録

参考にしたサイト様