【Python】よく使う関数

関数をよく忘れるので覚書き。

配列の逆順

l = [0, 1, 2, 3, 4]
for i in (reversed(l)):
print(i)

ファイルの読み書き

s = 'New file'
with open(path_w, mode='w') as f:
f.write(s)
with open(path_w) as f:
print(f.read())

URLエンコード

urllib.parse.urlparse("http://example.com/example.html?foo=bar&hoge=fuga")
urllib.parse.parse_qs("foo=bar&hoge=fuga")

日付のフォーマット

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

import datetime
now = datetime.datetime.now()

"{0:%Y-%m-%d %H:%M:%S}".format(now)
'2012-10-07 08:15:03'

文字列の検索

if ('<strong' in "test'") is False:

文字列の置換

Pythonで文字列を置換する:replace(), re.sub() | UX MILK

置換後の文字列 = 対象の文字列.replace(置換される文字列, 置換する文字列 [, 置換回数])

dst = src.replace("b", "B", 1)

置換後の文字列 = re.sub(正規表現, 置換する文字列, 置換される文字列 [, 置換回数])

import re
result = re.sub(r'[a-z]+', "0", text)

タグの除去

import re
re.sub("<.*?>","",【文字列】)

パスの取得

import os

filepath = './dir/subdir/filename.txt'

basename = os.path.basename(file)
print(basename)
# filename.txt

dirname = os.path.dirname(file)
print(dirname)
# ./dir/subdir

ラジオボタンの選択(with Selenium

driver.find_element_by_xpath("//input[@type='radio'][@value='1']").click()

チェックボックスのチェック(with Selenium

driver.find_element_by_xpath("//input[@id='order_terms']").click()

タイマーをセット

・一定時間後

def timer():
timeStr = datetime.now().strftime("%H:%M:%S")
print(timeStr)

t = threading.Timer(10, timer)
t.start()

・一定間隔で繰り返し

def timer():
global t

timeStr = datetime.now().strftime("%H:%M:%S")
print(timeStr)
t = threading.Timer(1, timer)
t.start()

t=threading.Thread(target=timer)
t.start()

pprint

php でいうと var_dump() みたいなもの

from pprint import pprint

pprint({})

as を付けると

from pprint import pprint as pp

pp({})

とも書ける

並び替え

dict.sort(key=lambda x:(x['column01'],x['column02']))
dict2 = dict.sorted(key=lambda x:(x['column01'],x['column02']))

lambda式

無名関数みたいなものかな?

payment2 = (lambda price,tax:price + (price * tax))(100,0.08)

辞書型の並び替えと合わせると

dict.sort(key=lambda x:(x['column01'],x['column02']))

JSON

JSON を扱う時に、「json」って変数名をつけると、ややこしいことになりますよ。

data = {"command": "googlehome",'content':msg}
jsonstr = json.dumps(data, ensure_ascii=False)
payload = {'json': jsonstr}
headers = {"content-type": "application/json"}
r = requests.put(url, data=json.dumps(payload), headers=headers)

ランダムな数字

import random

print(list(range(10)))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(random.randrange(10))
# 5

print(list(range(10, 20, 2)))
# [10, 12, 14, 16, 18]

print(random.randrange(10, 20, 2))
# 18

print(random.randint(50, 100))
# print(random.randrange(50, 101))
# 74

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA