0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python初心者】よく使うメソッドまとめ(Python3エンジニア認定基礎試験対応)

Posted at

Pythonでよく使われるメソッドを、ジャンルごとに簡単な説明と例とともに紹介します。
本記事はPython3エンジニア認定基礎試験の範囲にも対応しています。

ジャンル一覧

  • リスト型のメソッド
  • データ構造(deque)
  • 文字列メソッド
  • ファイル操作メソッド
  • JSON関連メソッド

リスト型のメソッド

append()

要素をリストの末尾に追加します。

list_data = [1, 2]
list_data.append(3)
print(list_data)  # [1, 2, 3]

extend()

リストを結合して要素を追加します。

list_data = [1, 2]
list_data.extend([3, 4])
print(list_data)  # [1, 2, 3, 4]

insert()

指定位置に要素を挿入します。

list_data = [1, 3]
list_data.insert(1, 2)
print(list_data)  # [1, 2, 3]

remove()

最初に見つかった指定の値を削除します。

list_data = [1, 2, 3, 2]
list_data.remove(2)
print(list_data)  # [1, 3, 2]

pop()

指定位置(デフォルトは末尾)の要素を削除して返します。

list_data = [1, 2, 3]
item = list_data.pop()
print(item)       # 3
print(list_data)  # [1, 2]

clear()

全ての要素を削除します。

list_data = [1, 2, 3]
list_data.clear()
print(list_data)  # []

index()

指定値のインデックス(位置)を返します。

list_data = [1, 2, 3]
print(list_data.index(2))  # 1

count()

指定値の出現回数を返します。

list_data = [1, 2, 2, 3]
print(list_data.count(2))  # 2

sort()

昇順に並べ替えます。

list_data = [3, 1, 2]
list_data.sort()
print(list_data)  # [1, 2, 3]

reverse()

要素の順番を逆にします。

list_data = [1, 2, 3]
list_data.reverse()
print(list_data)  # [3, 2, 1]

データ構造(deque)

deque(双方向キュー)は collections モジュールを使います。

popleft()

先頭の要素を取り出して削除します。

from collections import deque
d = deque([1, 2, 3])
print(d.popleft())  # 1
print(d)            # deque([2, 3])

文字列メソッド

rjust()

指定幅で右寄せにして埋め文字を追加します。

print('42'.rjust(5, '0'))  # '00042'

ljust()

指定幅で左寄せにして埋め文字を追加します。

print('42'.ljust(5, '0'))  # '42000'

center()

指定幅で中央寄せにして埋め文字を追加します。

print('42'.center(5, '0'))  # '04200'

zfill()

0埋めで右寄せします(符号付きも対応)。

print('42'.zfill(5))   # '00042'
print('-42'.zfill(5))  # '-0042'

ファイル操作メソッド

read()

ファイルの内容を全て読み込みます。

with open('example.txt', 'r') as f:
    content = f.read()
    print(content)

readline()

1行ずつ読み込みます。

with open('example.txt', 'r') as f:
    line = f.readline()
    print(line)

write()

ファイルに文字列を書き込みます。

with open('example.txt', 'w') as f:
    f.write('Hello\n')

tell()

現在のファイル位置を返します。

with open('example.txt', 'r') as f:
    print(f.tell())

seek()

ファイルの読み書き位置を変更します。

  • seek(0) は先頭へ移動
  • seek(offset, whence) の形式で、whence は以下を指定可能
    • 0: ファイルの先頭(デフォルト)

    • 1: 現在位置からの相対移動

    • 2: ファイル末尾からの相対移動(バイナリモード時のみ対応)

      with open('example.txt', 'rb') as f:
      f.seek(5) # 先頭から5バイト進む
      f.seek(-2, 2) # ファイル末尾から2バイト戻る

close()

ファイルを閉じます(with文を使えば明示的に不要)。

f = open('example.txt', 'r')
f.close()

JSON関連メソッド

load()

JSONファイルをPythonのオブジェクトとして読み込みます。

import json
with open('data.json', 'r') as f:
    data = json.load(f)
    print(data)

dumps()

PythonオブジェクトをJSON形式の文字列に変換します。

import json
data = {'name': 'Alice', 'age': 30}
json_str = json.dumps(data)
print(json_str)  # '{"name": "Alice", "age": 30}'

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?