Python基本文法覚書

雑な覚書。[コーディング規約](http://pep8-ja.readthedocs.io/ja/latest/)に書き方のお作法。

# 文字列
```python
str1 = "string value 1"
str2 = 'STRING VALUE 2'
# 複数行にまたがる文字列（改行文字含む。いわゆるヒアドキュメント）
str3 = """
this
is
here
document
"""
str4 = "   /hogehoge/   "

# 文字列置換
print(str1.replace("value", "new value"))

# split
print(str3.split('\n'))

# フォーマット（桁あわせ）
print(str1.rjust(100))
print(str1.ljust(100))
print(str1.zfill(100))

# 文字列検索
print(str1.startswith("string"))
print(str1.startswith("stRing"))
print('st' in str1)
print('ST' in str1)

# 先頭・末尾の空白削除
print(str4)
print(str4.lstrip())
print(str4.rstrip())

# 数値変換（Pythonでは型の宣言は不要だが、Perlと違い自動の型変換は行われないので、明示的に型変換要）
str5 = '100'
str6 = '100.6'
print(int(str5) + 10)
print(float(str6) + 10.0)

# 複素数
complexNum = 0 + 1J
print(complexNum ** 2)
```

# 日付
```python
import datetime as dt

dateToday = dt.date.today()
dateAndTimeToday = dt.datetime.today()
print(dateToday)
print(dateAndTimeToday)
print(dateAndTimeToday.year)
print(dateAndTimeToday.month)
print(dateAndTimeToday.day)
print(dateAndTimeToday.hour)
print(dateAndTimeToday.minute)
print(dateAndTimeToday.second)
print(dateAndTimeToday.microsecond)
print(dateAndTimeToday.isoformat())
print(dateAndTimeToday.strftime("%Y/%m/%d %H:%M:%S"))
print(dateToday + dt.timedelta(days=1))
newDate = dt.datetime(2018, 1, 1)
print(newDate + dt.timedelta(days=10))
delta = dateAndTimeToday - newDate
print(delta.days)
```

# 配列
```python
# タプル：長さ変更不可能な配列（shiracamus様コメントより追記：要素も変更不可つまりimmutable。ただしmutableな要素なら変更可能）
tpl = (1, 2, 3, [1, 2, 3])
print(tpl)
print(tpl[0])
tpl[3][0] = 999
print(tpl)

# リスト：長さ変更可能な配列
lst = [1, 2, 3]
print(lst)
print(lst[0])
lst.append("hoge")
print(lst)
lst.insert(0, "first")
obj = lst.pop(1)
print(obj)
print(lst)
lst.remove(2)
print(lst)
print(lst.index("first"))
print(lst.__len__())
print(lst.count(1))

# ディクショナリ
dic = {"year" :"2018", "month":'1', "day":"20"}
print(dic)
print(dic["year"])
print(dic.get("month"))
print(dic.get("hoge", "NOT FOUND"))
del dic["year"]
print(dic)
print(dic.keys())
print(dic.values())
for key, value in dic.items():
   print(key + ": " + value)

print("YEAR" in dic)
print("month" in dic)

# セット：重複を許さないリスト（順序は意味なし）
st = {1, 2, 3, 4, 4, 5}
print(st)                   # "4"はひとつだけ保持
emptySet = set()            # 空のセット生成
emptySet.add('hoge')
emptySet.update({"hoge1", "hoge2", "hoge3"})
print(emptySet)
emptySet.remove("hoge1")    # 削除対象が存在しない場合はエラー
emptySet.discard("hoge2")
print(emptySet)
frozenSet = frozenset({"hoge1", "hoge2","hoge3","hoge4"})
print(frozenSet)

# スライス: シーケンス（タプル、リスト、文字列など）から範囲指定して要素を取得
testlist = ["hoge1","hoge2","hoge3","hoge4","hoge5"]
print(testlist[0:5:1])
print(testlist[::-1])   # 逆順
```

# 引数: sys.argvのリストで[0]は実行ファイル名
```python
import sys

args = sys.argv
print(args)
from sys import argv
arg = argv
print(arg)

# パスの生成
import os
DIR1 = "c:\hoge"
DIR2 = "hoge"
print(os.path.join(DIR1, DIR2))
```

# 分岐
```python
v = input("enter number: ")
iv = int(v)
if iv == 1:
   print(1)
elif iv == 2:
   print(2)
elif iv == 10:
   pass # no-op(nothing to do)
else:
   print(3)
```

# 繰り返し
```python
for char in "hogehoge":
   print(char)

lst1 = [["key1","value1"],["key2","value2"]]
print(lst1)
for key,value in lst1:
   print("key: " + key + " value: " + value)

i = 0
while True:
   i = i + 1
   if(i % 3 == 0):
       continue
   elif(i % 5 == 0):
       print(i)
   elif(i == 22):
       break
   else:
       continue

for i in range(1, 10):
   print(i, end="")
```

# 例外処理
```python
import traceback

try:
   10 / 0
except:
   print(traceback.format_exc())
finally:
   pass # nothing to do
```

# 関数定義
```python
def test_func1(*args):
   print(args)
   for arg in args:
       print(arg)

def test_func2(**kwargs):
   print(kwargs)
   for argkey in kwargs:
       print("key: " + argkey + "; value: " + kwargs[argkey])

test_func1(1, 2, 3)
test_func2(key1="100", key2="200")
```

# クラス宣言
```python
class TestClass:
   def __init__(self):
       pass
   def hoge(self, i, j):
       print(i + j)

   @classmethod
   def clsmethod(cls):
       cls.hoge(cls, 1, 2)

   @staticmethod
   def stcmethod():
       print("hoge")

tcInstance = TestClass()
tcInstance.clsmethod()
tcInstance.stcmethod()
tcInstance.hoge(1, 100)

class CtxMgr:
   url = ""
   def get_url(self):
       return self.__url

   def set_url(self, value):
       self.__url = value

   def del_url(self):
       del self.__url

   def __enter__(self):
       print("entered")

   def __exit__(self,exc_type,exc_value,traceback):
       print("exiting")
       print(exc_type)
       print(exc_value)
       print("exitted")

   url = property(get_url, set_url, del_url, "url's docstring")

with CtxMgr():
   print("main")
```

# property
```python
import configparser

iniconfig = configparser.ConfigParser()
iniconfig.read("./config.ini", "UTF-8")
print(iniconfig.get("global", "param1"))
print(iniconfig.get("mysql", "mparam1"))
i = iniconfig.get("mysql", "mparam1")
j = iniconfig.get("mysql", "mparam2")
print(i + j)    # 値は文字列
print(int(i) + int(j))
```

# enumerate
```python
lst = ["hoge", "hogehoge", "hogehogehoge"]
for idx,val in enumerate(lst):
   print("index: " + str(idx) + ", value: " + val)
```

# 集合演算
```python
set1 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}
set2 = {"2", "3"}
set3 = {"1", "11"}
print(set2.isdisjoint(set1))   # 含まない場合にTrue
print(set2.issubset(set1))     # 全て含む場合にTrue
print(set1.issuperset(set2))   # 全て含む場合にTrue
print(set1.union(set3))        # 論理和（いずれかに含まれる要素）
print(set1.intersection(set3)) # 論理積（両方に含まれる要素）
print(set1.difference(set3))   # 差集合（重複要素は落とされる）
print(set1.symmetric_difference(set3)) # 排他的論理和（いずれか一方のみに含まれる要素）

# 内包表記
lst = [i for i in range(1,10)]
print(lst)
dct = {str(i): i for i in range(1,10)}
print(dct)
set_ = {str(i) for i in range(1,10)}
print(sorted(set_))
```