021_py_mojisuuti_jisyo - kotaproj/study_zenpan GitHub Wiki

pythonの文字列と数値の変換メモ

文字列→数値

10進数の文字列からintへ変換

>>> moji = '123'
>>> int(moji)
123

16進数の文字列からintへ変換

>>> ba = b'0f'
>>> ba
b'0f'
>>> int(ba, 16)
15

数値→文字列

intから16進数表記の文字列("0x"つき)

>>> a = 127
>>> hex(a)
'0x7f'

intから16進数表記の文字列(桁付加)

>>> a = 127
>>> format(a, '08x')
'0000007f'
>>> format(a, '08X')
'0000007F'

int ⇒ bytes

http://ni4muraano.hatenablog.com/entry/2017/02/05/102919

num = 255
num.to_bytes(2, 'big') # 2バイト、ビッグエンディアン、b'\x00\xff'と出力される

bytes ⇒ int

int.from_bytes(b'\x00\xff', 'big') # 255と出力される

文字列→辞書への変換

import ast

str = "{'名前':'太郎', '身長':'165', '体重':'60'}"
dic = ast.literal_eval(str)
print(dic['名前'])
print(type(dic))

↓実行結果↓
太郎
<class 'dict'>
>>> import ast
>>> s = "{'name':'twilite','temp':'7.3','hum':'77.16','pressure':'998'}"
>>> print(ast.literal_eval(s))
{'name': 'twilite', 'temp': '7.3', 'hum': '77.16', 'pressure': '998'}
>>>

バイト列の相互変換

encode/decode

>>> 'abcd'.encode()
b'abcd'
>>> b'abcd'.decode()
'abcd'

encode/decode - エンコーディング指定

>>> 'abcd'.encode(encoding='utf-8')
b'abcd'
>>> b'abcd'.decode(encoding='utf-8')
'abcd'

不正なバイト遭遇した場合にデフォルトはエラー

>>> b'\xff'.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

↑の不正バイト遭遇に代替文字に置き換える

>>> b'\xff'.decode('utf-8', 'replace')
'�'

キーワード引数を指定

>>> b'\xff'.decode(encoding='utf-8', errors='replace')
'�'
>>> str(b'\xff', encoding='utf-8', errors='replace')
'�'

文字列とバイト列の変換には bytes および str 関数

>>> bytes('abcd', encoding='utf-8', errors='replace')
b'abcd'
>>> str(b'abcd', encoding='utf-8', errors='replace')
'abcd'

文字列プレフィックス指定で、16進数の文字列から変換する

print(int('0o10', 0))
print(int('0x10', 0))
# 2
# 8
# 16
⚠️ **GitHub.com Fallback** ⚠️