メインコンテンツにスキップ

文字列処理

文字列の作成

様々な方法

# シングルクォート
name = 'Python'

# ダブルクォート
message = "Hello, World!"

# トリプルクォート(複数行)
text = """첫 번째 줄
두 번째 줄
세 번째 줄"""

poem = '''장미는 빨갛고
제비꽃은 파랗다'''

# エスケープシーケンス
quote = "He said, \"Hello!\""
path = "C:\\Users\\Documents"
new_line = "첫 줄\n두 번째 줄"
tab = "이름\t나이"

# raw文字列(エスケープを無視)
path = r"C:\Users\Documents"

文字列のインデックスとスライス

インデックス

text = "Python"

# 正のインデックス(左から: 0, 1, 2...)
print(text[0]) # P
print(text[1]) # y
print(text[5]) # n

# 負のインデックス(右から: -1, -2, -3...)
print(text[-1]) # n
print(text[-2]) # o
print(text[-6]) # P

# エラー
# print(text[10]) # IndexError

スライス

text = "Python Programming"

# [開始:終了] - 終了は含まない
print(text[0:6]) # Python
print(text[7:18]) # Programming

# 省略可能
print(text[:6]) # Python(最初から)
print(text[7:]) # Programming(最後まで)
print(text[:]) # Python Programming(全体)

# 負のインデックス
print(text[-11:]) # Programming
print(text[:-12]) # Python

# ステップを指定 [開始:終了:ステップ]
print(text[::2]) # Pto rgamn(2文字ごと)
print(text[::-1]) # gnimmargorP nohtyP(逆順)

# 実用例
url = "https://www.example.com"
domain = url[8:-4] # www.example
print(domain)

文字列の演算

連結と繰り返し

# 連結(+)
first = "Hello"
second = "World"
greeting = first + " " + second
print(greeting) # Hello World

# 繰り返し(*)
line = "=" * 20
print(line) # ====================

border = "-" * 10
print(f"{border} 제목 {border}")
# ---------- 제목 ----------

# 複数の文字列を結合
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Python is awesome

比較

# 等しい/等しくない
print("hello" == "hello") # True
print("hello" != "Hello") # True

# 大小比較(辞書順)
print("apple" < "banana") # True
print("apple" < "Apple") # False(大文字が先)

# 含まれるかどうか
text = "Python Programming"
print("Python" in text) # True
print("Java" in text) # False
print("Java" not in text) # True

文字列メソッド

大文字小文字の変換

text = "Hello, Python!"

print(text.upper()) # HELLO, PYTHON!
print(text.lower()) # hello, python!
print(text.capitalize()) # Hello, python!
print(text.title()) # Hello, Python!
print(text.swapcase()) # hELLO, pYTHON!

# 実用例 - ユーザー入力の正規化
user_input = " YES "
if user_input.strip().lower() == "yes":
print("확인되었습니다")

検索と確認

text = "Python Programming"

# 検索
print(text.find("Python")) # 0(最初の位置)
print(text.find("Java")) # -1(見つからない)
print(text.index("Programming")) # 7
# print(text.index("Java")) # ValueError

# カウント
print(text.count("o")) # 1
print(text.count("m")) # 3

# 開始/終了の確認
print(text.startswith("Python")) # True
print(text.endswith("ing")) # True

# 含まれるかの確認
print("gram" in text) # True

文字タイプの確認

# アルファベットのみ
print("abc".isalpha()) # True
print("abc123".isalpha()) # False

# 数字のみ
print("123".isdigit()) # True
print("12.3".isdigit()) # False

# アルファベット+数字
print("abc123".isalnum()) # True
print("abc 123".isalnum()) # False

# 空白のみ
print(" ".isspace()) # True
print(" a ".isspace()) # False

# 大文字/小文字
print("ABC".isupper()) # True
print("abc".islower()) # True

# 実用例 - パスワード検証
password = "Pass123"
has_digit = any(c.isdigit() for c in password)
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)

if len(password) >= 8 and has_digit and has_upper and has_lower:
print("강한 비밀번호입니다")

空白の削除

text = "   hello world   "

print(text.strip()) # "hello world"(両側)
print(text.lstrip()) # "hello world "(左)
print(text.rstrip()) # " hello world"(右)

# 特定の文字を削除
url = "https://example.com/"
print(url.strip("https://")) # example.com/
print(url.rstrip("/")) # https://example.com

# 実用例 - CSVパース
data = " 홍길동, 25, 서울 "
parts = [part.strip() for part in data.split(",")]
print(parts) # ['홍길동', '25', '서울']

変換と置換

text = "Hello, Python!"

# 置換
print(text.replace("Python", "World")) # Hello, World!
print(text.replace("l", "L")) # HeLLo, Python!
print(text.replace("l", "L", 1)) # HeLlo, Python!(1つだけ)

# 分割
words = text.split(", ")
print(words) # ['Hello', 'Python!']

csv = "홍길동,25,서울"
data = csv.split(",")
print(data) # ['홍길동', '25', '서울']

# 結合
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence) # Python is fun

# 特定の文字で結合
print("-".join(words)) # Python-is-fun

# 行の分割
text = """첫 줄
두 번째 줄
세 번째 줄"""
lines = text.splitlines()
print(lines) # ['첫 줄', '두 번째 줄', '세 번째 줄']

整列

# 左揃え
print("Python".ljust(10)) # "Python "
print("Python".ljust(10, "-")) # "Python----"

# 右揃え
print("Python".rjust(10)) # " Python"
print("Python".rjust(10, "0")) # "0000Python"

# 中央揃え
print("Python".center(10)) # " Python "
print("Python".center(10, "*"))# "**Python**"

# 実用例 - テーブル出力
print("이름".ljust(10) + "나이".rjust(5))
print("홍길동".ljust(10) + "25".rjust(5))
print("김철수".ljust(10) + "30".rjust(5))

文字列フォーマット

f-string(Python 3.6+、推奨)

name = "홍길동"
age = 25
height = 175.5

# 基本的な使い方
print(f"이름: {name}, 나이: {age}")

# 式
print(f"내년 나이: {age + 1}")
print(f"키(cm): {height}")

# フォーマット指定
price = 1234567
print(f"가격: {price:,}원") # 가격: 1,234,567원

pi = 3.14159265
print(f"원주율: {pi:.2f}") # 원주율: 3.14

# 整列と幅
print(f"{'Python':>10}") # " Python"
print(f"{'Python':<10}") # "Python "
print(f"{'Python':^10}") # " Python "
print(f"{'Python':*^10}") # "**Python**"

# 進数表現
num = 255
print(f"10진수: {num}") # 10진수: 255
print(f"16진수: {num:x}") # 16진수: ff
print(f"8진수: {num:o}") # 8진수: 377
print(f"2진수: {num:b}") # 2진수: 11111111

format()メソッド

# 位置ベース
print("이름: {}, 나이: {}".format("홍길동", 25))

# インデックス指定
print("{1}, {0}".format("World", "Hello")) # Hello, World

# 名前指定
print("이름: {name}, 나이: {age}".format(name="홍길동", age=25))

# フォーマット指定
print("가격: {:,}원".format(1234567))
print("비율: {:.1%}".format(0.856))

%フォーマット(レガシー)

name = "홍길동"
age = 25

print("이름: %s, 나이: %d" % (name, age))
print("비율: %.2f%%" % 85.678)

実践例

メール検証

def validate_email(email):
"""簡単なメール検証"""
# @が含まれているか確認
if "@" not in email:
return False

# @を基準に分割
parts = email.split("@")
if len(parts) != 2:
return False

local, domain = parts

# ローカルパートとドメインの検証
if not local or not domain:
return False

# ドメインに.が含まれているか確認
if "." not in domain:
return False

return True

# テスト
emails = [
"user@example.com", # ✅
"invalid.email", # ❌
"@example.com", # ❌
"user@", # ❌
]

for email in emails:
result = "유효" if validate_email(email) else "무효"
print(f"{email}: {result}")

テキストマスキング

def mask_phone(phone):
"""電話番号をマスクする"""
if len(phone) == 11:
return phone[:3] + "****" + phone[7:]
elif len(phone) == 10:
return phone[:3] + "***" + phone[6:]
return phone

def mask_email(email):
"""メールをマスクする"""
local, domain = email.split("@")
if len(local) <= 2:
masked_local = local[0] + "*"
else:
masked_local = local[0] + "*" * (len(local) - 2) + local[-1]
return f"{masked_local}@{domain}"

# 使用
print(mask_phone("01012345678")) # 010****5678
print(mask_email("hong@example.com")) # h**g@example.com

文字列アナライザー

def analyze_string(text):
"""文字列の詳細分析"""
return {
"길이": len(text),
"단어수": len(text.split()),
"대문자": sum(1 for c in text if c.isupper()),
"소문자": sum(1 for c in text if c.islower()),
"숫자": sum(1 for c in text if c.isdigit()),
"공백": sum(1 for c in text if c.isspace()),
"특수문자": sum(1 for c in text if not c.isalnum() and not c.isspace())
}

text = "Hello Python 2024! Welcome to coding."
result = analyze_string(text)

print("=== 문자열 분석 ===")
for key, value in result.items():
print(f"{key}: {value}")

URLパーサー

def parse_url(url):
"""URLをパースする"""
# プロトコルを分離
if "://" in url:
protocol, rest = url.split("://", 1)
else:
protocol = "http"
rest = url

# パスを分離
if "/" in rest:
domain, path = rest.split("/", 1)
path = "/" + path
else:
domain = rest
path = "/"

# ポートを分離
if ":" in domain:
domain, port = domain.split(":")
else:
port = "80" if protocol == "http" else "443"

return {
"프로토콜": protocol,
"도메인": domain,
"포트": port,
"경로": path
}

url = "https://www.example.com:8080/api/users"
result = parse_url(url)

for key, value in result.items():
print(f"{key}: {value}")

Unicodeとエンコーディング

Unicodeの扱い

# 韓国語
text = "안녕하세요"
print(len(text)) # 5

# 絵文字
emoji = "😀🎉"
print(len(emoji)) # 2

# Unicodeコードポイント
print(ord("A")) # 65
print(chr(65)) # A
print(ord("가")) # 44032
print(chr(44032)) # 가

エンコード/デコード

text = "안녕하세요"

# エンコード(文字列→バイト)
utf8_bytes = text.encode("utf-8")
print(utf8_bytes) # b'\xec\x95\x88\xeb\x85\x95...'

euckr_bytes = text.encode("euc-kr")
print(euckr_bytes)

# デコード(バイト→文字列)
decoded = utf8_bytes.decode("utf-8")
print(decoded) # 안녕하세요

よくある質問

Q1. 文字列は不変ですか?

A: はい、文字列は不変(immutable)です。

text = "hello"
# text[0] = "H" # ❌ TypeError

# 新しい文字列を作成
text = "H" + text[1:] # ✅ "Hello"

Q2. +とjoin、どちらが速いですか?

A: 多くの文字列を連結する場合はjoinが速いです。

# ❌ 遅い(多くの文字列生成)
result = ""
for i in range(1000):
result += str(i)

# ✅ 速い
result = "".join(str(i) for i in range(1000))

Q3. 複数行文字列でのインデントは?

A: textwrapモジュールを使用します

from textwrap import dedent

text = dedent("""
첫 번째 줄
두 번째 줄
세 번째 줄
""").strip()

print(text)
# 첫 번째 줄
# 두 번째 줄
# 세 번째 줄

Q4. 正規表現は必要ですか?

A: 複雑なパターンマッチングには必要です。

import re

# 簡単な場合:文字列メソッド
email = "user@example.com"
if "@" in email and "." in email:
print("이메일 형식")

# 複雑な場合:正規表現
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if re.match(pattern, email):
print("유효한 이메일")

次のステップ

文字列処理をマスターしました!

重要ポイント:
✅ インデックスとスライス
✅ 様々な文字列メソッド
✅ 文字列フォーマット(f-string)
✅ 検索、変換、検証
✅ 実践的な例

次のステップ: リストとタプルでコレクションを学びましょう!