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】Python `string` ライブラリ解説

0
Posted at

はじめに

Python で文字列を扱う場面は非常に多く、
入力検証・ID生成・パスワード処理・ブルートフォースなど、
セキュリティや業務ロジックの基盤になることも珍しくありません。

そんなときに役立つのが、標準ライブラリ string です。

string は地味ですが、

  • 可読性が高い
  • バグを減らせる
  • セキュリティ的にも安全

という 「知ってる人ほど使うライブラリ」 です。


string ライブラリとは

string は Python 標準ライブラリで、
よく使われる文字集合(アルファベット・数字・記号など)
定数として提供します。

import string

よく使う定数一覧(必須)

アルファベット

string.ascii_lowercase  # abcdefghijklmnopqrstuvwxyz
string.ascii_uppercase  # ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_letters   # 上記2つの結合

用途例

  • ID・コード生成
  • フォーマット検証
  • ブルートフォース文字集合

数字

string.digits  # 0123456789

用途例

  • 数値フォーマット検証
  • PINコード生成
  • 連番ID

16進数

string.hexdigits
# 0123456789abcdefABCDEF

用途例

  • ハッシュ文字列検証
  • トークンチェック
  • HEX形式入力のバリデーション

記号

string.punctuation
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

用途例

  • パスワード強度判定
  • 危険文字チェック
  • フィルタ回避文字検出

空白・制御文字

string.whitespace  # ' \t\n\r\x0b\x0c'
string.printable   # 表示可能な全文字

実践的な使用例

例1:フォーマット検証

「最初3桁は数字、最後は大文字1文字」

import string

def is_valid_code(s: str) -> bool:
    return (
        len(s) == 4 and
        s[:3].isdigit() and
        s[3] in string.ascii_uppercase
    )

print(is_valid_code("007A"))  # True
print(is_valid_code("12aB"))  # False

'A' <= c <= 'Z' より安全で明確


例2:総当たり生成(ブルートフォース)

import string

codes = [
    str(i).zfill(3) + ch
    for ch in string.ascii_uppercase
    for i in range(1000)
]

# password_list = [
#     f"{i:03d}{ch}"
#     for ch in string.ascii_uppercase
#     for i in range(1000)
# ]

print(codes[:5])
# ['000A', '001A', '002A', '003A', '004A']

ポイント

  • 仕様がコードから一瞬で分かる
  • 文字集合の変更が容易

例3:ランダムトークン生成

import random
import string

def random_token(length=16):
    chars = string.ascii_letters + string.digits
    return ''.join(random.choice(chars) for _ in range(length))

※ セキュリティ用途では secrets を使いましょう。


stringstr メソッドの違い

種類 役割
string 文字集合・定数
str 文字列オブジェクトの操作
s = "abc123"

s.isdigit()        # False
s.upper()          # 'ABC123'

string.digits      # '0123456789'
  • 条件定義 → string
  • 加工処理 → str

セキュリティ視点での活用

パスワード強度チェック

def strong_password(pw: str) -> bool:
    return (
        any(c in string.ascii_lowercase for c in pw) and
        any(c in string.ascii_uppercase for c in pw) and
        any(c in string.digits for c in pw) and
        any(c in string.punctuation for c in pw)
    )

危険文字の検出

any(c in string.punctuation for c in user_input)

よくあるアンチパターン

❌ 自前で書く

"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

⭕ 正解

string.ascii_uppercase

理由

  • タイポ防止
  • 仕様が明確
  • 読み手に優しい

まとめ

  • string文字集合の公式カタログ
  • 可読性・安全性・保守性が一気に向上
  • 入力検証・生成処理では必須
  • 「地味だけど、プロは使う」ライブラリ

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?