Python 標準ライブラリ

NumPy Matplotlib GUI エクセル PyGame

Python3公式 標準ライブラリ

文字列

text = 'abcde'

# 検索 見つかった場所を返す。見つからないときは-1
pt = text.find("bc")

# 置換 
text2 = text.replace("bc", "xx")

# 埋め込み(format)
name = 'りんご'
price =100
text = "商品名:{0} 価格:{1}".format(name, price)

# 埋め込み(f文字列)
text = f"商品名:{name} 価格:{price}"

# カンマによる分割
text = "abc,def,ghi"
tlist = text.split(",")

# 改行による分割
text = "abc\ndef\nghi"
tlist = text.splitlines()

# 結合
tlist = ['abc', 'def', 'ghi']
text = ",".join(tlist) # カンマ区切りで結合

# 左右の空白、タブ、改行除去
text = "  abc \n"
text = text.strip() # "abc"

# 小文字
text2 = text.lower()

# 大文字
text2 = text.upper()

# スライス
text = 'abcde';
print( text[1:4] ) # bcd
print( text[:3] ) # abc
print( text[2:] ) # cde
print( text[-2:] ) # de

数学関数

import math

num = 10.5
print( math.floor(num) ) # 切り捨て
print( math.ceil(num) ) # 切り上げ
print( math.pow(2, 5) ) # 2の5乗
print( math.sqrt(2) ) # ルート2
print( math.pi ) # 円周率

print( math.radians(180) ) # 角度からラジアンに変換
print( math.sin(math.radians(180)) ) # sin(引数はラジアン)
print( math.cos(math.radians(180)) ) # cos(引数はラジアン)
print( math.tan(math.radians(180)) ) # tan(引数はラジアン)

turtleで長さ100の45度の線を書く

import turtle
import math

x = math.cos(math.radians(45)) * 100
y = math.sin(math.radians(45)) * 100
turtle.setpos(x, y)

turtle.done() # 終了

日付

from datetime import date, datetime, timedelta

print(date.today()) # 今日の日付
print(datetime.now()) # 現在日時

d = date(2019, 7, 7) # 特定日付
print(d.year) # 年
print(d.month) # 月
print(d.day) # 日
print(d.weekday()) # 曜日 月=0 ~日=6

t = datetime(2019, 7, 1, 12, 10, 23) # 特定日時
print(t.hour) # 時
print(t.minute) # 分
print(t.second) # 秒

# 文字列で表示
print(t.strftime("%Y-%m-%d %H:%M:%S"))

# 文字列から
hi = "2020/05/01"
d = datetime.strptime(hi, "%Y/%m/%d")
print(d)

# 日付加算
d = datetime.now()
d = d + timedelta(weeks=1) # 他にdays,minutes,seconds
print(d)

ファイルの読み書き

一行ずつ読み込み

f = open("test.txt", encoding='UTF-8')

for line in f:
    line = line.rstrip() # 改行削除
    print(line)

f.close()

withを使うと自動でcloseされる

with open("test.txt", encoding='UTF-8') as f:
    for line in f:
        line = line.rstrip()
        print(line)

全て読み込み

文字列として読み込み read()

f = open("test.txt", encoding='UTF-8')

s = f.read()
print(s)

f.close()

1行ずつリストとして読み込み readlines()

f = open("test.txt", encoding='UTF-8')

list = f.readlines()
for line in list:
    print(line, end='')	# 改行がかぶらないように

f.close()

書き込み

文字列

f = open("test.txt", "w", encoding='UTF-8')

f.write("test\n")

f.close()

withを使うと自動でcloseされる

with  open("test.txt", "w", encoding='UTF-8') as f:
	f.write("abc\n")

リスト

list = ["abc", "def"]

f = open("test.txt", "w", encoding='UTF-8')
f.writelines(list) # 改行されない

f.close()

追記は a モードで開く

f = open("test.txt", "a", encoding='UTF-8')

f.write("test\n")

f.close()

乱数

import random

num = random.randint(1, 6)  # 1~6の乱数
print( num )

lst = [5, 8, 9, 7, 4]
num = random.choice(lst) # ランダムに選択
print( num )

random.shuffle(lst) # シャッフル
print( lst )

ファイル・フォルダ操作

import os

# カレントフォルダ移動
os.chdir("c:\\temp")

# カレントフォルダ
print( os.getcwd() )


# フォルダ作成
os.mkdir('myfolder')

# フォルダ削除
os.rmdir('myfolder')

# ファイル削除
os.remove('test1.txt')

# ファイル名変更
os.rename('test1.txt', 'test2.txt')

ファイル一覧の取得

import os

# 全ファイル表示
flist = os.listdir("c:\\temp")
for f in flist:
    print(f)

os.chdir("c:\\temp")
# カレントフォルダ全ファイル
flist = os.listdir()
for f in flist:
    if os.path.isfile(f): # ファイルかどうかを判定
        print("File:", f)
    else:
        print("Folder:", f)

パスの操作

import os

# フォルダとファイルに分ける
path = "c:\\temp\\test.txt"
folder, file = os.path.split(path)
print(folder) # C:\temp
print(file) # test.txt

# フォルダとファイルをつなげる
path2 = os.path.join(folder, 'test2.txt')
print(path2)

セキュアハッシュ

import hashlib

key = "abc"

# MD5ハッシュ
h = hashlib.md5(key.encode()).hexdigest()
print(h)

# sha1ハッシュ
h = hashlib.sha1(key.encode()).hexdigest()
print(h)

# sha256ハッシュ
h = hashlib.sha256(key.encode()).hexdigest()
print(h)

正規表現

検索

import re

body = "This is a pen"
pattern = "Th.*"

result = re.match(pattern, body)
if result:
    print("発見")
else:
    print("なし")
.任意の文字
+直前の文字1文字以上
*直前の文字0文字以上
()グループ化
[0-9]0~9の文字。\dと同じ。
^行頭
$行末

置換

import re

body = "This is a pen"
pattern = "(p.*)"
after = r"super\1"

result = re.sub(word, pattern, body)
print(result)

分割

import re

body = "apple orage,ichigo"
pattern = "[ ,]"

data = re.split(pattern, body)
print(data)

JSON

JSON文字列に変換

json.dumps(コレクション)

import json

data = {"name":"ringo", "tanka":100}

j = json.dumps(data)

print(j)

JSON文字列から変換

json.loads(JSON文字列)

import json

j = '{"name":"ringo", "tanka":100}'

data = json.loads(j)

print(data["name"])