ii = 3
if ii < 0:
print('負')
elif ii == 0:
print('ゼロ')
else:
pirnt('正')
s1 = 'hoge' + str(1)
s2 = 'hoge' + str(1)
print(s1 == s2)
# => True
print(s1 is s2)
# => False
list = [1, 2, 3, 4, 5]
ii = 3
# 含まれているかチェック
if ii in list:
print('included')
# 含まれていないかチェック
if 6 not in list:
print('not included')
# 整数
ii = 0
if ii:
print('not zero')
else:
print('zero')
# => zero
# 0.0 も False として判定される
# 文字列
str = ''
if str:
print('not empty')
else:
print('empty')
# => empty 空文字列も False として判定される
# リスト
list = []
if list:
print('not empty')
else:
print('empty')
# => empty
# 空タプル (), 空ディクリショナリ {}, 空Set () も False として判定される
False と判定されるのは 0, 0.0, (空文字列), 空リスト, 空ディクショナリ, 空Set, 空タプル
while ループを抜けると else が実行される。
(break で抜けた場合は else は実行されない。)
idx = 1
sum = 0
while idx <= 10:
if idx == 11:
break
sum += idx
idx += 1
else:
print(sum)
# => 55
sum = 0
for ii in range(10):
sum += ii
else:
print(sum)
# => 45
range(10)
は range(0, 10, 1)
と同じ
0 から 1 ずつ増えて 9(10未満)で終わり。
(for も break で抜けた場合は else は実行されない。)
names = ['hoge', 'fuga']
for idx, name in enumerate(names):
print(idx, name)
# => 0 hoge, 1 fuga
dic = { 'id': 1, 'name': 'hoge' }
for k, v in dic.items():
print(k, v)
# => id 1, name hoge
items() がタプルを返し、それをアンパックして k, v に代入する。
try:
ii = int('123')
print(ii)
list = []
print(list[0])
except ValueError as ex:
print(ex)
except Exception as ex:
print(ex)
else:
print('no error')
finally:
print('finally')
print('It isn\'t xxx')
print("It is \"hoge\"")
print(r"That \n means new line")
capital = 'Tokyo'
country = 'Japan'
print(f'Tha capital of {country} is {capital}')
str = ('No1'
'No2'
'No3')
行末にバックスラッシュを付ける
str = 'No1'\
'No2'\
'No3'
print("""No1
No2
No3""")
# これは次のと同じ結果になる
print("""\
No1
No2
No3\
""")
str = "Hawaii"
print(str[2]) # w
str = "Hawaii"
print(str[-1]) # i
str = "Hawaii"
print(str[2:5]) # wai
str = "Hawaii"
print(str[:3]) # Haw
str = "Hawaii"
print(str[2:]) # waii
str = "Hawaii"
print(str[-3:]) # aii
str = "Hawaii"
print(str[:-3]) # Haw
%p: AM/PM
import datetime
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
import datetime
now = datetime.datetime.now()
print('{}.{:03d}'.format(now.strftime('%Y-%m-%d %H:%M'), round(now.microsecond / 1000)))
date = datetime.datetime.strptime('20240102', '%Y%m%d')
date = datetime.datetime.strptime('20240102091530', '%Y%m%d%H%M%S')
date = datetime.datetime.strptime('20240102091530123000', '%Y%m%d%H%M%S%f')
# 不正な日付を datetime に変換しようとすると「ValueError: unconverted data remains: 2」エラーになる。
date = datetime.datetime.strptime('20240132', '%Y%m%d')
=> 「remains: 2」は、最後の 2が変換できなかった、という意味。
10 // 3 # => 3
2 ** 8 # => 256
list = [1,2,3,4,5]
tuple = (1,2,3,4,5)
tuple = ()
tuple = (1,)
tuple = (1,2)
hoge, fuga = tuple
print(hoge, fuga) # 1 2
dic = { 'id': 1, 'name': 'hoge' }
# 別の書き方
dic2 = dict( id=1, name='hoge' )
dic3 = dict([('id', 1), ('name', 'hoge')])
id = dic['identity']
# => KeyError がスローされる
id = dic.get('identity')
print(type(id)) # <class 'NoneType'>
# => get で取り出すと NoneType が返る
print(id is None)
# => True
s = { 1, 2, 3, 2, 4, 5}
print(set) # {1, 2, 3, 4, 5} => 重複した 2 が 1つにまとめられる
list = [ 1, 2, 3, 2, 4, 5 ]
s = set(list) # {1, 2, 3, 4, 5}
def func(hoge, fuga, foo=3):
print("hoge=", hoge)
print("fuga=", fuga)
print("foo=", foo)
# キーワード引数で呼び出す
func(fuga="fuga!", hoge="hoge!", foo=1)
# 1番目は位置引数で、2つ目からはキーワード引数で呼び出す
func("hoge#", foo=1, fuga="fuga#")
# 1, 2番目は一引数で、3番目はデフォルト引数で呼び出す
func("hoge$", "fuga$")
デフォルト引数に空のリストをセットする場合、リストが再利用されることに注意する。
def func(num, hoge=[]):
hoge.append(num) # 2回目以降に呼び出す時は、前回呼び出された時のリストに対して追加される。
return hoge
list = func(1)
print(list) # [1]
list = func(2)
print(list) # [1, 2]
これを避けるには、デフォルト引数に None を指定し、関数内で None の場合にリストを初期化する。
def func(num, hoge=None):
if hoge is None: # 何回呼び出されても、毎回引数が省略された場合はリストを初期化する。
hoge = []
hoge.append(num)
return hoge
list = func(1)
print(list) # [1]
list = func(2)
print(list) # [2] <= 2だけになる
def func(**args):
print(args)
for k, v in args.items():
print(k, '=', v)
func(state='Hawaii', island='Oafu', city='Honolulu')
パラメーター名の前に * を付けるとタプルとして受け取る。
def func(*args):
print(args)
state, island, city = args
print('state=', state, ', island=', island, ', city=', city)
func('Hawaii', 'Oafu', 'Honolulu')
def func(state, *args):
print('state=', state)
for arg in args:
print(arg)
func('Hawaii', 'Oafu', 'Honolulu')
def func(country, *states, **args):
print('country=', country)
print('states=', states)
for k, v in args.items():
print(k, '=', v)
# USA は位置パラメーター, California, New York, Florida はタプル, 残りはディクショナリとして渡す。
func('USA', 'California', 'New York', 'Florida', state='Hawaii', island='Oafu', city='Honolulu')
パラメーターで渡された関数を実行する前後に処理を追加し、そのデコレーターを関数と関連付けて実行する。
def debug_message(func):
def wrapper(*args, **kwargs):
print('args:', args)
result = func(*args, **kwargs)
print('result:', result)
return result
return wrapper
def trace_message(func):
def wrapper(*args, **kwargs):
print('start:', func.__name__)
result = func(*args, **kwargs)
print('end:', func.__name__)
return result
return wrapper
@trace_message
@debug_message
def traced_func(country, *states, **args):
print('country=', country)
print('states=', states)
for k, v in args.items():
print(k, '=', v)
return 'OK'
# USA は位置パラメーター, California, New York, Florida はタプル, 残りはディクショナリとして渡す。
traced_func('USA', 'California', 'New York', 'Florida', state='Hawaii', island='Oafu', city='Honolulu')
class File:
def __init__(self, file_name, mode):
self.file_obj = None
self.file_name = file_name
self.mode = mode
def __enter__(self):
self.file_obj = open(self.file_name, self.mode)
return self.file_obj
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file_obj:
self.file_obj.close()
with File('example.txt', 'r') as f:
contents = f.read()
print(contents)
class Resource:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"リソース {self.name} を取得しました")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
print(f"リソース {self.name} で例外が発生しました: {exc_type}")
else:
print(f"リソース {self.name} を解放しました")
with Resource("my_resource") as resource:
# リソースを使用する
print(f"リソース {resource.name} を使用しています")
class Hoge():
def __init__(self, name: str):
self._name = name
@property # @property を指定することで、括弧なしの name で値を取得できるようになる。
def name(self):
return self._name
hoge = Hoge('Taro')
print(hoge.name) # name で値を取り出せる
print(hoge.name()) # @property の付いたメソッドを呼び出そうとするとエラーになる(TypeError: 'str' object is not callable)
hoge.name = 'Jiro' # <= name への代入はエラーになる(AttributeError: can't set attribute)
print(hoge.name)
hoge._name = 'Saburo' # しかし _name には直接代入できてしまう
print(hoge.name)
class Hoge():
def showName(self):
print('My name is', self.name) # クラス Hoge に name というフィールドはない
hoge = Hoge()
hoge.name = 'Taro' # しかし name というフィールドに値をセットできてしまう。
print(hoge.name)
hoge.showName() # 外から追加したフィールドは、クラスの中からも参照できる。
class Hoge():
def __init__(self, name: str):
self.__name = name
@property
def name(self):
return self.__name
def showName2(self):
print(self.name2)
hoge = Hoge('Taro')
print(hoge.name) # Taro
hoge.__name = 'Saburo' # __name に Saburo をセットできてしまう
print(hoge.__name) # Saburo
print(hoge.name) # Taro <= Hoge クラス内の __name は置き換わらず Taro のまま、つまり別の変数が作成されている。
import abc
class MetaClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def hello(self):
pass
class Hoge(MetaClass):
def __init__(self):
print('init')
meta = MetaClass() # <= TypeError: Can't instantiate abstract class MetaClass with abstract methods hello
hoge = Hoge() # <= TypeError: Can't instantiate abstract class Hoge with abstract methods hello
@abc.abstractmethod が付与されたメソッドを継承先で実装していないと例外がスローされる。
class Hoge():
class_value = 'hoge'
__class_value = 'private hoge'
@classmethod
def class_hello(cls):
print(cls.class_value) # クラス変数を参照する場合はパラメーターの cls を付ける
@staticmethod
def static_hello():
print(Hoge.class_value) # クラス変数を参照する場合はクラス名を付ける
print(Hoge.__class_value) # プライベータなクラス変数をクラス内から参照
Hoge.class_hello() # hoge
Hoge.static_hello() # hoge
print(Hoge.class_value) # hoge <= 直接クラス変数を参照することも可能
print(Hoge.__class_value) # private なクラス変数を外から参照すると AttributeError: type object 'Hoge' has no attribute '__class_value'
import os
file_path = '/home/hoge/readme.txt'
print(os.path.dirname(file_path)) # '/home/hoge'
import os
main_dir = '/home'
user = 'hoge'
file_name = 'readme.txt'
print(os.path.join(main_dir, user, file_name)) # '/home/hoge/readme.txt'
import os
file_path = '/home/hoge/readme.txt'
print(os.path.basename(file_path)) # 'readme.txt'
import os
file_path = '/home/hoge/readme.txt'
print(os.path.splitext(file_path)[0]) # '/home/hoge/readme'
print(os.path.splitext(file_path)[1]) # 'txt'
import sys
print(sys.argv[0]) # 自身のスクリプト名
print(sys.argv[1]) # 最初の引数
text = sys.stdin.read()
for line in sys.stdin:
line = line.rstrip()
def main():
# メイン処理
if __name__ == '__main__':
main()
python3 -c "import sys; print(sys.path)"
python -m http.server 8000
サンプル by Gemini
import codecs
def convert_and_replace(input_file, output_file, replace_char):
with open(input_file, 'r', encoding='utf-8') as f_in:
data = f_in.read()
try:
# SJISに変換
converted_data = data.encode('shift-jis')
except UnicodeEncodeError as e:
# 変換できない文字があった場合
print(f"変換エラー: {e}")
# 代替文字に変換
converted_data = data.encode('shift-jis', errors='replace', replacement=replace_char)
with open(output_file, 'w', encoding='shift-jis') as f_out:
f_out.write(converted_data.decode('shift-jis'))
if __name__ == '__main__':
input_file = 'input.txt'
output_file = 'output.txt'
replace_char = '?' # SJISにない文字を置き換える文字
convert_and_replace(input_file, output_file, replace_char)
または
import codecs
def convert_and_replace_with_codecs(input_file, output_file, replace_char):
with open(input_file, 'r', encoding='utf-8') as f_in:
data = f_in.read()
try:
# SJISに変換
encoder = codecs.getencoder('shift-jis')
converted_data, _ = encoder(data, errors='replace', replacement=replace_char)
except UnicodeEncodeError as e:
print(f"変換エラー: {e}")
with open(output_file, 'w', encoding='shift-jis') as f_out:
f_out.write(converted_data)
if __name__ == '__main__':
input_file = 'input.txt'
output_file = 'output.txt'
replace_char = '?' # SJISにない文字を置き換える文字
convert_and_replace_with_codecs(input_file, output_file, replace_char)