[Python] Replace does not replace string of multiple characters, but with one character it...

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following data set, in which I want to replace yes and no with 1 and 0, respectively. But it does not work. It somehow only works, if I replace only one letter, but then it results in 1es or 0o, which is not favorable.

    Here is the dataset

    35,5 no yes no no no no no

    35,9 no no yes yes yes yes no

    35,9 no yes no no no no no

    36,0 no no yes yes yes yes no


    Here is the code

    fString = open("diagnosis.data", "r")
    fFloat = open("diagnosis.csv", "w")

    for line in fString:
    line = line.replace(",", ".")
    line = line.replace("\t", ",")
    line = line.replace("yes", "1")
    line = line.replace("no", "0")
    line = line.replace("\r\n", "\n")
    fFloat.write(line)
    fString.close()
    fFloat.close()


    and the resulting dataset

    35.5,no,yes,no,no,no,no,no਍ഀ

    35.9,no,no,yes,yes,yes,yes,no਍ഀ

    35.9,no,yes,no,no,no,no,no਍ഀ

    36.0,no,no,yes,yes,yes,yes,no਍ഀ

    Somehow there appear these boxes at the end of a line?

    Continue reading...

Compartilhe esta Página