[PR] この広告は3ヶ月以上更新がないため表示されています。
ホームページを更新後24時間以内に表示されなくなります。

技術のメモ箱

Python/よく使うコード

文字列操作

やりたいこと実装
文字列長の取得
len(str)
文字列の切り取り
str[2:5]  # 配列のスライスを参照
指定文字列を含むか
'hoge' in str
文字列を指定文字で区切る
str = 'One,Two,Three'
str.split(',') # ['One', 'Two', 'Three']
指定文字で区切った文字列を作る
list = ['One', 'Two', 'Three']
','.join(list)  # 'One,Two,Three'
正規表現による置換
import re
re.sub('<[^<>]+>', '@', str)

数値操作

やりたいこと実装
乱数生成(0~1)
from random import random
random() # 0.37444887175646646
乱数生成(指定範囲)
from random import randrange
randrange(5) # 0~4
randrange(2, 5) # 2~4
randrange(2, 9, 2) # 2, 4, 6, 8
数値判定
'123'.isdecimal()

日付操作

今の日時を取得

from datetime import datetime
datetime.today().strftime('%Y%m%d%H%M')

ファイル操作

withを使うことで、openしたファイルオブジェクトは終了時に自動でcloseされる

ファイルの存在確認

os.path.isfile(filepath)
os.path.isdir(dirpath)
os.path.exists(path)

ファイル入力

with open('input.txt', encoding='UTF-8') as f:
    str = f.read()  # ファイル全体を文字列として取得
    line = f.readlines()  # ファイル全体をリストとして取得
    for l in f:  # ファイルを一行ずつ読み込み
        print(l)

ファイル出力

with open('output.txt', encoding='UTF-8', mode='a') as f:  # 新規・上書き
    f.write('str')
    print('output_string', file=f)

ファイルリスト取得

from pathlib import Path
directory = Path(r'./')
for filename in directory.glob(r'**/*.html'):
    print(filename)

grep

from pathlib import Path
rootdir = Path(r'./')

for filename in rootdir.glob(r'**/*.html'):
    with open(filename, encoding='UTF-8') as file:
        for line in file:
            if 'grep_string' in line:
                print(line)
pagetop