はじめに
Python3エンジニア認定基礎試験の対策として自分用に執筆しています。
この記事はPython・執筆学びたての初心者が執筆しています。間違いがあるかもしれませんので、ぜひ各項目にある参考文献も確認してください。また、誤りがあればコメントで教えていただけると幸いです。
入力と出力
>>> year = 2024
>>> f'This year is {year}'
'This year is 2024'
>>> integer_value = 42
>>> float_value = 3.14159
>>> # 整数のフォーマット
>>> formatted_integer = '{:04d}'.format(integer_value) # 4桁でゼロ埋め
>>> print(f'Formatted Integer: {formatted_integer}')
Formatted Integer: 0042
Formatted Float: 3.14
str()
, repr()
はどちらも表現を返すものであり、違いは人間が読むかインタプリタが読むか。
フォーマット済み文字列リテラル
値のフォーマット方式を制御できる
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
':'の後ろに整数を付けると、其のフィールドの最小の文字幅を指定できる。
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
文字列のformat()
はメソッドに渡されたオブジェクトに置き換えるもの
>>> print('{0}は{1}型の言語です'.format('Python', 'インタプリタ'))
Pythonはインタプリタ型の言語です
>>> print('{0}と{1}'.format('Java', 'Python'))
JavaとPython
>>> print('{1}と{0}'.format('Java', 'Python'))
PythonとJava
zfill()
を使うと数値文字列の左側をゼロ詰めする
>>> '12'.zfill(4)
0012
ファイルの読み書き
ファイルを開くには open()
を利用する。
open('ファイル名', 'モード', 'encodeタイプ')
モードは'r'
は読み出し専用、'w'
は書き込み専用、'a'
は追記用に開く。
使ったら、close()
で閉じること。
>>> f = open('filename', 'w', encoding="utf-8")
>>> f.close()
close()
をし忘れないためにもwith
の使用を推奨されている。
>>> with open('filename', encoding="utf-8") as f:
... read_data = f.read()
ファイルオブジェクトのメソッドには以下のようなものがある
>>> f.read() # ファイル全体を文字列として読み込み
>>> f.readline() # ファイルから1行だけを読み込み
>>> f.write('content') # 引数をファイルに書き込み
>>> f.tell() # ファイル中における現在の位置を示す整数を返す
jsonの読み込み
>>> import json
>>> x = json.load(f)
>>> json.dumps(x)
[1, 'sample', 'list']
参考文献