Python:Python Type Casting und Typumwandlung mit Beispielen
Python•Typkonvertierung

Python Type Casting und Typumwandlung mit Beispielen

Python bietet explizite Konvertierungskonstruktoren wie int(), float(), str(), bool(), list() und set(), um Daten sicher zwischen inkompatiblen Typen umzuwandeln.

Syntax

new_value = target_type(original_value)

Parameter & Werte

Wichtige Bestandteile und zulässige Werte für diese Struktur:

ParameterTypBeschreibung
target_typeType constructorint, float, str, bool, list, tuple oder set.
original_valueAny convertible objectDer umzuwandelnde Wert.

Ausführbares Code-Beispiel

In Compilra ausführbar

Führe dieses vollständige Beispiel direkt aus, ohne Python lokal zu installieren:

# Explicit Type Casting in Python
raw_price = "49.95"
quantity_str = "3"

# Convert strings to float and int
unit_price = float(raw_price)
quantity = int(quantity_str)
subtotal = unit_price * quantity

# Boolean truthiness conversion
empty_list = []
active_items = ["Laptop", "Mouse"]

print(f"Unit Price: ${unit_price} ({type(unit_price).__name__})")
print(f"Quantity:   {quantity} ({type(quantity).__name__})")
print(f"Subtotal:   ${subtotal:.2f}")
print(f"Empty list bool:  {bool(empty_list)}")
print(f"Active items bool: {bool(active_items)}")
Erwartete Ausgabe:
Unit Price: $49.95 (float)
Quantity:   3 (int)
Subtotal:   $149.85
Empty list bool:  False
Active items bool: True

So funktioniert es: Schritt für Schritt

  • Zeilen 6-7: Wandelt numerische Strings in float- und int-Primitive um.
  • Zeile 8: Multipliziert erfolgreich einen Float mit einer Ganzzahl.
  • Zeilen 15-16: Zeigt Pythons Truthiness: leere Container werden als False ausgewertet.

Kernkonzepte

  • float("49.95") parst Dezimalzahlen aus Text.
  • int("3") extrahiert Ganzzahlwerte; nicht-numerische Strings lösen einen ValueError aus.
  • bool() wandelt leere Strings, 0, None und leere Collections in False um.

Häufiger Fehler: Einen Gleitkomma-String direkt an int() übergeben

int("49.95") wirft einen ValueError. Wandle zuerst in float und danach in int um.

❌ Falsch
price = int("49.95") # ValueError: invalid literal for int()
✅ Richtig
price = int(float("49.95")) # Correct: turns 49.95 into 49

Verwandte Python-Tutorials & Compiler

Python auf Compilra ausführen und testen

Führe dieses Code-Snippet mit vorab bereitgestellter Standardeingabe (stdin) in Compilras Cloud-Compiler aus.

Python Online-Compiler