🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

Vollständiger Leitfaden zu Python-String-Methoden 2026: Alle Methoden mit Beispielen

⏱️3 min read  ·  617 words

Python-String-Methoden gehören zu den am häufigsten verwendeten Tools im Toolkit eines jeden Python-Entwicklers. Im Jahr 2026 ist die Beherrschung der String-Manipulation für Web Scraping, Datenbereinigung, API-Arbeit und Textverarbeitung unerlässlich. Dieser vollständige Leitfaden deckt alle wichtigen String-Methoden mit praktischen Beispielen ab.

Grundlegende String-Methoden

# String creation and basic info
text = "  Hello, Python World!  "
print(len(text))          # 24 (including spaces)
print(type(text))         # <class 'str'>

# Case transformation
print(text.upper())       # "  HELLO, PYTHON WORLD!  "
print(text.lower())       # "  hello, python world!  "
print(text.title())       # "  Hello, Python World!  "
print(text.capitalize())  # "  hello, python world!  " (only first char)
print(text.swapcase())    # "  hELLO, pYTHON wORLD!  "

# Whitespace removal
print(text.strip())       # "Hello, Python World!" (both sides)
print(text.lstrip())      # "Hello, Python World!  " (left only)
print(text.rstrip())      # "  Hello, Python World!" (right only)
print(text.strip("!. ")) # removes those chars from both ends

Such- und Testmethoden

s = "Hello, Python World!"

# Finding substrings
print(s.find("Python"))      # 7 (returns -1 if not found)
print(s.index("Python"))     # 7 (raises ValueError if not found)
print(s.rfind("l"))          # 14 (search from right)
print(s.count("l"))          # 3

# Boolean checks
print(s.startswith("Hello"))  # True
print(s.endswith("!"))        # True
print(s.startswith(("Hi", "Hello")))  # True (tuple of prefixes)

# Content checks
print("abc123".isalnum())    # True (only alphanumeric)
print("Hello".isalpha())     # True (only letters)
print("12345".isdigit())     # True (only digits)
print("   ".isspace())       # True (only whitespace)
print("HELLO".isupper())     # True
print("hello".islower())     # True
print("Python 3.12".isprintable())  # True

Modifikationsmethoden

# Replace
s = "Hello World Hello"
print(s.replace("Hello", "Hi"))          # "Hi World Hi"
print(s.replace("Hello", "Hi", 1))       # "Hi World Hello" (max 1 replacement)

# Split and join
csv = "Alice,Bob,Carol,Dave"
print(csv.split(","))         # ["Alice", "Bob", "Carol", "Dave"]
print(csv.split(",", 2))      # ["Alice", "Bob", "Carol,Dave"] (max 2 splits)

lines = "line1
line2
line3"
print(lines.splitlines())    # ["line1", "line2", "line3"]

# Join — build string from list
words = ["Python", "is", "awesome"]
print(" ".join(words))       # "Python is awesome"
print("-".join(words))       # "Python-is-awesome"
print("".join(["a","b","c"])) # "abc"

# Padding and alignment
print("hello".center(11, "*"))  # "***hello***"
print("hi".ljust(10, "."))      # "hi........"
print("hi".rjust(10, "."))      # "........hi"
print("42".zfill(5))            # "00042" (zero-fill for numbers)

Format- und Vorlagenmethoden

# f-strings (best, Python 3.6+)
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
print(f"Pi: {3.14159:.2f}")        # Pi: 3.14
print(f"Hex: {255:#010x}")         # Hex: 0x000000ff
print(f"1000000: {1_000_000:,}")   # 1000000: 1,000,000

# format() method
print("Hello, {}!".format(name))
print("{0} + {1} = {2}".format(2, 3, 2+3))
print("{name} is {age}".format(name="Bob", age=25))

# Template strings (safe for user input)
from string import Template
t = Template("Hello, $name!")
print(t.substitute(name="Alice"))    # "Hello, Alice!"
print(t.safe_substitute())           # "Hello, $name!" (no KeyError)

# encode/decode
s = "Hello, 世界"
encoded = s.encode("utf-8")   # bytes
decoded = encoded.decode("utf-8")  # string back

Reale String-Verarbeitung

# Clean user input
def clean_username(raw: str) -> str:
    return raw.strip().lower().replace(" ", "_")[:30]

# Parse CSV line
def parse_csv_line(line: str) -> list[str]:
    return [field.strip().strip('"') for field in line.split(",")]

# Validate email (simple)
def is_valid_email(email: str) -> bool:
    email = email.strip().lower()
    return "@" in email and "." in email.split("@")[1]

# Extract numbers from string
import re
text = "I have 3 cats and 12 dogs"
numbers = [int(n) for n in re.findall(r'\d+', text)]  # [3, 12]

# Camel to snake case
def camel_to_snake(name: str) -> str:
    s = re.sub(r'([A-Z]+)([A-Z][a-z])', r'_', name)
    return re.sub(r'([a-z\d])([A-Z])', r'_', s).lower()

# Truncate with ellipsis
def truncate(text: str, max_len: int = 100) -> str:
    return text[:max_len-3] + "..." if len(text) > max_len else text

Python-String-Methoden sind die Grundlage der Textverarbeitung. Master-Strip/Split/Join für die Datenbereinigung, Suchen/Ersetzen für die Texttransformation und Formatzeichenfolgen für die Ausgabe. Die Kombination aus F-Saiten (modern) und Split/Join deckt 90 % der alltäglichen Saitenarbeit ab.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇬🇧 English🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी