Python: String in int oder float parsen mit UliEngineering
Du kannst leicht einen String entweder als Ganzzahl (int) oder als Fließkommazahl (float) parsen mit der UliEngineering-Python-Bibliothek:
parse_int_or_float.py
from UliEngineering.Utils.Parser import parse_int_or_float
# Ganzzahl-Strings parsen
value = parse_int_or_float("42")
print(f"Parse '42': {value} (Typ: {type(value).__name__})")
# Fließkomma-Strings parsen
value = parse_int_or_float("3.14")
print(f"Parse '3.14': {value} (Typ: {type(value).__name__})")
# Wissenschaftliche Notation parsen
value = parse_int_or_float("1.5e3")
print(f"Parse '1.5e3': {value} (Typ: {type(value).__name__})")Beispielausgabe
parse_int_or_float_output.txt
Parse '42': 42 (Typ: int)
Parse '3.14': 3.14 (Typ: float)
Parse '1.5e3': 1500.0 (Typ: float)Diese Funktion bestimmt automatisch, ob eine Ganzzahl oder eine Fließkommazahl zurückgegeben wird, basierend auf dem Eingabestring. Ganzzahl-Strings ohne Dezimalpunkt werden als int zurückgegeben, während Strings mit Dezimalpunkt oder wissenschaftlicher Notation als float zurückgegeben werden. Dies ist nützlich, wenn man numerische Eingaben verarbeiten muss, die entweder Ganzzahl oder Fließkomma sein können, ohne den Typ im Voraus zu kennen.
Verwandte Beiträge
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow