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初心者】stringモジュールまとめ(文字列定数と使い方)

Posted at

Pythonのstringモジュールは、文字列処理に便利な定数や関数がまとめられた標準ライブラリです。

この記事では、主に定数について整理し、使い方と出力結果を確認します。
学習の記録として、自分用のチートシートも兼ねてまとめました。

stringモジュールのインポート

まずはモジュールのインポートからです。

import string

文字種ごとの定数一覧と出力例

1. ascii_letters(英小文字 + 英大文字)

print(string.ascii_letters)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

2. ascii_lowercase(英小文字)

print(string.ascii_lowercase)
abcdefghijklmnopqrstuvwxyz

3. ascii_uppercase(英大文字)

print(string.ascii_uppercase)
ABCDEFGHIJKLMNOPQRSTUVWXYZ

4. digits(数字)

print(string.digits)
0123456789

5. hexdigits(16進数の文字)

print(string.hexdigits)
0123456789abcdefABCDEF

6. punctuation(記号)

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

7. whitespace(空白文字)

print(repr(string.whitespace))
' \t\n\r\x0b\x0c'

※空白(スペース、タブ、改行など)をまとめたものです。repr() を使うと見えない文字も確認できます。

よくある用途例

✅ ランダムなパスワードを生成する

import secrets
import string

letters = string.ascii_letters + string.digits
password = ''.join(secrets.choice(letters) for _ in range(8))
print(password)

→ 英数字からランダムに8文字のパスワードを生成できます。

✅ 入力値が数字かどうかチェック

user_input = '12345'
if all(c in string.digits for c in user_input):
    print("数字だけで構成されています")

補足:stringモジュールと組み合わせやすい関数

  • secrets.choice():ランダムに1文字選ぶ(セキュアな乱数)
  • random.choice():ランダムに1文字選ぶ(簡易的)
  • ''.join(...):リストの文字を1つの文字列にまとめる
  • repr():見えない文字(空白など)を確認する

まとめ

  • string モジュールは、よく使う文字列(英字・数字・記号など)を手軽に扱うための便利なツールです。
  • 特に ascii_letters, digits, punctuation は試験でもよく出題されるので覚えておきます。
  • 実用例としては、パスワード生成や入力チェックなどに役立ちます。

今後も学習を進めながら、他の標準ライブラリについてもまとめていきたいと思います。

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?