1
1

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)操作ガイド

1
Posted at

はじめに

Pythonにおける文字列(str)操作は、
ログ解析・Web開発・セキュリティ・データ処理など、あらゆる分野で必須となる基礎スキルです。

一見シンプルに見えますが、

  • イミュータブル(不変)
  • スライスの仕様
  • join / split の使い分け
    など、理解不足だとバグや性能劣化の原因にもなります。

本記事では、実務で本当に使うstring操作を中心に整理します。


1. 文字列の基本特性

s = "Hello"

イミュータブル(immutable)

Pythonの文字列は 変更不可 です。

s[0] = "h"   # TypeError

文字列操作は「破壊的変更」ではなく、
常に新しい文字列を生成します。

s = "h" + s[1:]

2. インデックスとスライス

s = "Hello, Python"
s[0]      # 'H'
s[-1]     # 'n'
s[0:5]    # 'Hello'
s[7:]     # 'Python'
s[::-1]   # 'nohtyP ,olleH'

スライス構文

s[start : end : step]
  • end含まれない
  • step = -1 で逆順

Python初心者〜中級者まで必ず一度は踏む罠。


3. 連結と繰り返し

"a" + "b"     # 'ab'
"a" * 3       # 'aaa'

大量連結時の注意

# 非推奨(遅い)
s = ""
for i in range(1000):
    s += str(i)

# 推奨(高速)
s = "".join(str(i) for i in range(1000))

join は性能面で圧倒的に有利です。


4. よく使う文字列メソッド

s = " Hello, Python! "
メソッド 説明
lower() 小文字化
upper() 大文字化
strip() 前後空白削除
replace(a, b) 置換
startswith() 前方一致
endswith() 後方一致
in 部分一致
"Py" in s   # True

5. split と join(最重要)

s = "apple,banana,orange"
lst = s.split(",")
",".join(lst)

覚え方

  • split → 文字列 → リスト
  • join → リスト → 文字列

👉 join文字列側のメソッド


6. 検索系メソッド

s = "Hello Python"
s.find("Python")   # 6(なければ -1)
s.index("Python")  # 6(なければ例外)
s.count("o")       # 2

find vs index

  • 例外が嫌なら find
  • 存在が前提なら index

7. f-string(現代Pythonの正解)

name = "Anna"
age = 25

f"{name} is {age} years old"

フォーマット指定も簡潔:

pi = 3.14159
f"{pi:.2f}"   # '3.14'

👉 format() や % 記法より可読性・安全性が高い


8. 判定系メソッド

"123".isdigit()     # True
"abc".isalpha()     # True
"abc123".isalnum()  # True
"   ".isspace()     # True

入力検証・ログ解析で頻出。


9. エンコードとデコード

s = "こんにちは"

b = s.encode("utf-8")
s2 = b.decode("utf-8")
  • strbytes の変換
  • 通信・暗号・ファイル処理では必須

10. よくある落とし穴

if s.find("Py"):
    print("found")

"Py" が先頭(0)だと False 判定

if s.find("Py") != -1:
    print("found")

まとめ

  • 文字列は 不変
  • slice / split / join / f-string を押さえれば実務対応可能
  • 大量処理では join
  • find と index の違いを理解する
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?