[Python] Python string[] and float weird behavior? [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Python to communicate between a RaspberryPi and an ESP32, so I send strings back and forth and "decode" to get the data I need.

    So for my test string I have: input_string = "2;068;060;076;030;000;000;000;000;000;000;000;000;000;000;000;000;000;000"

    I'm trying to get the "068" characters (which should be [2:4], right?) to convert them into a float with:

    float(input_string[2:4])


    Which only yields "6.0" as an awswer.

    I then tried a bunch of different values and print them off to understand what was going on:

    print(input_string)
    print(input_string[2:4])
    print(input_string[2:5])
    print(float(input_string[2:5]))


    And this returns:

    "2;068;060;076;030;..."
    "06"
    "068;"
    "68.0"


    I mean, why does [2:4] return "06" and [2:5] return "068;"? Also, since "068;" has a non-number character, it should return an error when used in "float()", and it just doesn't.

    Am I missing something too obvious?

    Edit: fixed the output part in the correct identation

    Continue reading...

Compartilhe esta Página