Skip to content

Python - Formatumwandlung str -> float

Python3
  • Seit einigen wenigen Tagen, beschäftige ich mich damit wie man ein paar Daten von einer Webseite ausliest und diese dann entsprechend weiterverarbeitet.

    Dabei musste ich so ziemlich das erste Mal in Python rechnen und was kam - Fehler! Die Formate passte nicht. Somit musste ich mich damit beschäftigen, wie man so was umwandelt.

    Nehmen wir an, ich erhalte solche Daten

    Formatierte Stringwerte aus dem Scraping ['20.605,00', '3.685,50', '3.013,80']
    

    Nehmen wir weiterhin an, es sind € Werte und ich möchte diese addieren. Die Liste von oben hat den Namen result.

    # String Werte umwandeln in float, damit ich damit rechnen kann
    f2 = []
    for count, value in enumerate(result):
        print("Value as String", value)
        # Tausenderpunkt entfernen!
        p = value.replace('.', '')
        # Umwandeln in float, dazu das Komma in einen Punkt umwandeln
        f = float(p.replace(',', '.'))
        # Floatwerte abspeichern
        f2.append(f) # f2.append(f)
    
    # Kontrollausgabe
    print(f2[0])
    print(f2[1])
    print(f2[2])
    
    addition = f2[0] + f2[1] + f2[2]
    print("Ergebnis Addition", addition)
    

    Ordentlich formatiert wird das mit

    import locale
    print(locale.format_string("%.2f", addition, grouping = True))
    

    Jetzt hatte ich mir noch die Frage gestellt, wie bekommt man da ein paar Zeilen weg. Ich hatte das schon mal irgendwo gemacht, wusste aber nicht mehr wo. Also Dokumentation im Netz gelesen und folgendes gefunden.

    # String Werte umwandeln in float, damit ich damit rechnen kann
    f2 = []
    for count, value in enumerate(result):
        print("Value as String", value)
        # Umwandeln in float, Tausenderpunkt entfernen und Komma in einen  Punkt umwandeln
        f = float((value.replace('.', '')).replace(',', '.'))
        # Floatwerte abspeichern
        f2.append(f) # f2.append(f)
    

    Auf den Wert (value) wird hier als erstes folgendes angewendet

    value.replace('.', '')
    

    Wir entfernen den Tausenderpunkt.

    Danach

    replace(',', '.')
    

    Das Komma für die Nachkommastellen ersetzen wir durch einen Punkt.

    Das Klammern wir mal alles entsprechend ein, verbinden das mit einem Punkt und auf den kompletten Ausdruck wenden wir ein Float an. Ferrtig 🙂

    Ok, es hat deutlich länger gedauert, bis ich das alles verstanden habe. Mehr Zeit als diesen Beitrag zu tippen, aber wie immer das Ergebnis zählt.

    Sollte hier Blödsinn stehen, oder noch besser, sollte jemand bessere Lösungen haben, bitte hier drunter. Ich freue mich über jede konstruktive Antwort.

    Ich weiß das einige Variablen Namen nicht PEP konform sind

  • 0 Stimmen
    5 Beiträge
    128 Aufrufe
    FrankMF

    Hab ChatGPT nochmal nach der Installation auf einem Production Server befragt.

    ChatGPT

    Certainly! Here's a short example of the steps you can follow to deploy a Flask application on a production server using Nginx and Gunicorn:

    Prepare your server:

    Set up a server (e.g., using a cloud provider like AWS, DigitalOcean, or a dedicated server) and ensure it has a clean, up-to-date installation of a Linux distribution (e.g., Ubuntu or CentOS).

    Install required software:

    Install necessary software packages on your server. You'll need Python, pip (Python package manager), Nginx, and Gunicorn. You can use your distribution's package manager (e.g., apt for Ubuntu or yum for CentOS) to install these dependencies.

    Deploy your Flask application:

    Copy your Flask application code and any required dependencies to your server.

    Set up a virtual environment (optional but recommended):

    Create a virtual environment for your Flask application to isolate its dependencies. You can use venv or virtualenv for this purpose.

    Install Flask and any required Python packages within your virtual environment:

    pip install flask

    Test your Flask application:

    Ensure your Flask application runs correctly within your server's virtual environment.

    Configure Gunicorn:

    Create a Gunicorn configuration file (e.g., gunicorn_config.py) to specify the settings for running your Flask application. Here's a simple example: workers = 4 # Number of Gunicorn worker processes bind = '0.0.0.0:8000' # The address and port Gunicorn should listen on

    Start Gunicorn:

    Start Gunicorn with your Flask application: gunicorn -c gunicorn_config.py your_app:app

    Configure Nginx:

    Create an Nginx server block (often located in /etc/nginx/sites-available) to define how Nginx should handle incoming requests. Here's a simplified example: server { listen 80; server_name your_domain.com www.your_domain.com; location / { proxy_pass http://127.0.0.1:8000; # Pass requests to Gunicorn proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }

    Enable the Nginx server block and restart Nginx:

    sudo ln -s /etc/nginx/sites-available/your_config /etc/nginx/sites-enabled/ sudo nginx -t # Test Nginx configuration sudo systemctl restart nginx

    Configure your DNS:

    Point your domain name to your server's IP address.

    Secure your server (optional but recommended):

    Set up SSL/TLS certificates for your domain to enable HTTPS. You can use Let's Encrypt for free SSL certificates.

    Monitor your application:

    Set up monitoring tools and logs to keep track of your application's performance and troubleshoot any issues.

    These are the basic steps to deploy a Flask application on a production server with Nginx and Gunicorn. Please note that this is a simplified example, and there are many additional considerations, such as database configuration, security, and optimization, depending on your specific application and requirements. It's also important to keep your server and software up to date and follow security best practices to ensure the stability and security of your production environment.

    Das werde ich doch mal ausprobieren 😎

  • Pycharm - Umzug auf neuen Rechner

    Linux
    1
    0 Stimmen
    1 Beiträge
    52 Aufrufe
    Niemand hat geantwortet
  • PyPi - Pakete ein Sicherheitsproblem?

    Python3
    1
    0 Stimmen
    1 Beiträge
    66 Aufrufe
    Niemand hat geantwortet
  • Python - Frameworks

    Python3
    2
    0 Stimmen
    2 Beiträge
    76 Aufrufe
    FrankMF

    Und mal hier parken

  • Example Class

    Angeheftet Python3
    3
    0 Stimmen
    3 Beiträge
    103 Aufrufe
    FrankMF

    In meinem PywebIO Projekt tauchte heute ein alter Bekannter auf. Wenn ich einen Eintrag (innerhalb der Liste) löschte, war das etwas durcheinander 🤔

    Ja, den Fehler kenne ich schon was länger und stolper immer mal wieder drüber. Heute z.B.

    Also mal grübeln 🤓

    Das mache ich, wenn ich einen Eintrag lösche

    case 'Yes': # delete entrie BackupList.delete((line - 1)) # save json BackupList.save_json() # Load data from filesystem BackupList.load_json() # Reload Tab Backup backup()

    Ich mache folgendes

    lösche den Eintrag speicher die Liste lade die Liste baue den Tab wieder auf

    Das führt aber dazu, das meine Liste die als Objekt im Speicher steht nicht aktuell ist. Im Gegenteil, da ist dann etwas Unordnung. Ich brauchte also die Möglichkeit mein Objekt backups irgendwie zurückzusetzen.

    Mal gegoogelt und die Dinge sind manchmal wirklich total easy 🙂

    # clear dict backups.clear()

    Das leert das Objekt und im nächsten Schritt kann ich es wieder befüllen.

    Lösung case 'Yes': # delete entrie BackupList.delete((line - 1)) # save json BackupList.save_json() # clear dict backups.clear() # Load data from filesystem BackupList.load_json() # Reload Tab Backup backup()

    Problem erledigt. Damit ich das noch finde, wenn mein Kopf das nicht mehr hergibt, notiere ich das hier.

  • Python - Dict -> JSON und umgekehrt

    Python3
    1
    0 Stimmen
    1 Beiträge
    173 Aufrufe
    Niemand hat geantwortet
  • PyWebIO

    Angeheftet PyWebIO
    1
    0 Stimmen
    1 Beiträge
    157 Aufrufe
    Niemand hat geantwortet
  • Python - mehrsprachiges GUI

    Python3
    1
    0 Stimmen
    1 Beiträge
    111 Aufrufe
    Niemand hat geantwortet