Zum Hauptinhalt springen

String-Verarbeitung

String-Erstellung

Verschiedene Methoden

# Einfache Anführungszeichen
name = 'Python'

# Doppelte Anführungszeichen
message = "Hello, World!"

# Dreifache Anführungszeichen (mehrzeilig)
text = """첫 번째 줄
두 번째 줄
세 번째 줄"""

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

# Escape-Sequenzen
quote = "He said, \"Hello!\""
path = "C:\\Users\\Documents"
new_line = "첫 줄\n두 번째 줄"
tab = "이름\t나이"

# Raw-String (ignoriert Escape-Zeichen)
path = r"C:\Users\Documents"

String-Indizierung und Slicing

Indizierung

text = "Python"

# Positiver Index (von links: 0, 1, 2...)
print(text[0]) # P
print(text[1]) # y
print(text[5]) # n

# Negativer Index (von rechts: -1, -2, -3...)
print(text[-1]) # n
print(text[-2]) # o
print(text[-6]) # P

# Fehler
# print(text[10]) # IndexError

Slicing

text = "Python Programming"

# [Start:Ende] - Ende nicht eingeschlossen
print(text[0:6]) # Python
print(text[7:18]) # Programming

# Kann weggelassen werden
print(text[:6]) # Python (vom Anfang)
print(text[7:]) # Programming (bis zum Ende)
print(text[:]) # Python Programming (alles)

# Negativer Index
print(text[-11:]) # Programming
print(text[:-12]) # Python

# Schrittweite angeben [Start:Ende:Schritt]
print(text[::2]) # Pto rgamn (jeder 2. Buchstabe)
print(text[::-1]) # gnimmargorP nohtyP (umgekehrt)

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

String-Operationen

Verkettung und Wiederholung

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

# Wiederholung (*)
line = "=" * 20
print(line) # ====================

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

# Mehrere Strings verbinden
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Python is awesome

Vergleich

# Gleich/Ungleich
print("hello" == "hello") # True
print("hello" != "Hello") # True

# Größenvergleich (alphabetisch)
print("apple" < "banana") # True
print("apple" < "Apple") # False (Großbuchstaben zuerst)

# Enthält-Prüfung
text = "Python Programming"
print("Python" in text) # True
print("Java" in text) # False
print("Java" not in text) # True

String-Methoden

Groß-/Kleinschreibung umwandeln

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!

# Praktisches Beispiel - Benutzereingabe normalisieren
user_input = " YES "
if user_input.strip().lower() == "yes":
print("확인되었습니다")

Suchen und Prüfen

text = "Python Programming"

# Finden
print(text.find("Python")) # 0 (erste Position)
print(text.find("Java")) # -1 (nicht gefunden)
print(text.index("Programming")) # 7
# print(text.index("Java")) # ValueError

# Zählen
print(text.count("o")) # 1
print(text.count("m")) # 3

# Start/Ende prüfen
print(text.startswith("Python")) # True
print(text.endswith("ing")) # True

# Enthält-Prüfung
print("gram" in text) # True

Zeichentyp prüfen

# Nur Buchstaben
print("abc".isalpha()) # True
print("abc123".isalpha()) # False

# Nur Zahlen
print("123".isdigit()) # True
print("12.3".isdigit()) # False

# Buchstaben + Zahlen
print("abc123".isalnum()) # True
print("abc 123".isalnum()) # False

# Nur Leerzeichen
print(" ".isspace()) # True
print(" a ".isspace()) # False

# Groß-/Kleinbuchstaben
print("ABC".isupper()) # True
print("abc".islower()) # True

# Praktisches Beispiel - Passwortvalidierung
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("강한 비밀번호입니다")

Leerzeichen entfernen

text = "   hello world   "

print(text.strip()) # "hello world" (beide Seiten)
print(text.lstrip()) # "hello world " (links)
print(text.rstrip()) # " hello world" (rechts)

# Bestimmte Zeichen entfernen
url = "https://example.com/"
print(url.strip("https://")) # example.com/
print(url.rstrip("/")) # https://example.com

# Praktisches Beispiel - CSV-Parsing
data = " 홍길동, 25, 서울 "
parts = [part.strip() for part in data.split(",")]
print(parts) # ['홍길동', '25', '서울']

Umwandlung und Ersetzung

text = "Hello, Python!"

# Ersetzen
print(text.replace("Python", "World")) # Hello, World!
print(text.replace("l", "L")) # HeLLo, Python!
print(text.replace("l", "L", 1)) # HeLlo, Python! (nur 1x)

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

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

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

# Mit bestimmtem Zeichen verbinden
print("-".join(words)) # Python-is-fun

# Zeilen trennen
text = """첫 줄
두 번째 줄
세 번째 줄"""
lines = text.splitlines()
print(lines) # ['첫 줄', '두 번째 줄', '세 번째 줄']

Ausrichtung

# Linksbündig
print("Python".ljust(10)) # "Python "
print("Python".ljust(10, "-")) # "Python----"

# Rechtsbündig
print("Python".rjust(10)) # " Python"
print("Python".rjust(10, "0")) # "0000Python"

# Zentriert
print("Python".center(10)) # " Python "
print("Python".center(10, "*"))# "**Python**"

# Praktisches Beispiel - Tabellenausgabe
print("이름".ljust(10) + "나이".rjust(5))
print("홍길동".ljust(10) + "25".rjust(5))
print("김철수".ljust(10) + "30".rjust(5))

String-Formatierung

f-string (Python 3.6+, empfohlen)

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

# Grundlegende Verwendung
print(f"이름: {name}, 나이: {age}")

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

# Formatangabe
price = 1234567
print(f"가격: {price:,}원") # 가격: 1,234,567원

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

# Ausrichtung und Breite
print(f"{'Python':>10}") # " Python"
print(f"{'Python':<10}") # "Python "
print(f"{'Python':^10}") # " Python "
print(f"{'Python':*^10}") # "**Python**"

# Zahlensysteme
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()-Methode

# Positionsbasiert
print("이름: {}, 나이: {}".format("홍길동", 25))

# Index angeben
print("{1}, {0}".format("World", "Hello")) # Hello, World

# Name angeben
print("이름: {name}, 나이: {age}".format(name="홍길동", age=25))

# Format angeben
print("가격: {:,}원".format(1234567))
print("비율: {:.1%}".format(0.856))

%-Formatierung (Legacy)

name = "홍길동"
age = 25

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

Praktische Beispiele

E-Mail-Validierung

def validate_email(email):
"""Einfache E-Mail-Validierung"""
# @ enthalten prüfen
if "@" not in email:
return False

# Nach @ trennen
parts = email.split("@")
if len(parts) != 2:
return False

local, domain = parts

# Lokalen Teil und Domain validieren
if not local or not domain:
return False

# Domain enthält . prüfen
if "." not in domain:
return False

return True

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

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

Text-Maskierung

def mask_phone(phone):
"""Telefonnummer maskieren"""
if len(phone) == 11:
return phone[:3] + "****" + phone[7:]
elif len(phone) == 10:
return phone[:3] + "***" + phone[6:]
return phone

def mask_email(email):
"""E-Mail maskieren"""
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}"

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

String-Analyzer

def analyze_string(text):
"""Detaillierte String-Analyse"""
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-Parser

def parse_url(url):
"""URL parsen"""
# Protokoll trennen
if "://" in url:
protocol, rest = url.split("://", 1)
else:
protocol = "http"
rest = url

# Pfad trennen
if "/" in rest:
domain, path = rest.split("/", 1)
path = "/" + path
else:
domain = rest
path = "/"

# Port trennen
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 und Kodierung

Unicode verwenden

# Koreanisch
text = "안녕하세요"
print(len(text)) # 5

# Emoji
emoji = "😀🎉"
print(len(emoji)) # 2

# Unicode-Codepunkte
print(ord("A")) # 65
print(chr(65)) # A
print(ord("가")) # 44032
print(chr(44032)) # 가

Kodierung/Dekodierung

text = "안녕하세요"

# Kodierung (String → Bytes)
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)

# Dekodierung (Bytes → String)
decoded = utf8_bytes.decode("utf-8")
print(decoded) # 안녕하세요

Häufig gestellte Fragen

F1. Sind Strings unveränderlich?

A: Ja, Strings sind unveränderlich (immutable).

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

# Neuen String erstellen
text = "H" + text[1:] # ✅ "Hello"

F2. + vs join, welches ist schneller?

A: Bei vielen String-Verkettungen ist join schneller.

# ❌ Langsam (viele String-Erstellungen)
result = ""
for i in range(1000):
result += str(i)

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

F3. Wie handhabe ich Einrückungen in mehrzeiligen Strings?

A: Verwenden Sie das textwrap-Modul

from textwrap import dedent

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

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

F4. Brauche ich reguläre Ausdrücke?

A: Für komplexe Musterabgleiche sind sie notwendig.

import re

# Einfacher Fall: String-Methoden
email = "user@example.com"
if "@" in email and "." in email:
print("이메일 형식")

# Komplexer Fall: Reguläre Ausdrücke
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if re.match(pattern, email):
print("유효한 이메일")

Nächste Schritte

Sie haben die String-Verarbeitung gemeistert!

Zusammenfassung:
✅ Indizierung und Slicing
✅ Verschiedene String-Methoden
✅ String-Formatierung (f-string)
✅ Suchen, Umwandeln, Validieren
✅ Praktische Anwendungsbeispiele

Nächster Schritt: Lernen Sie Kollektionen in Listen und Tupel!