Covert categorical user input into numerical

Question:

so I’m trying to change the data that the user enters through the form into a string.

this is the code for the combobox

Status_bangunan_cb = Combobox(window, textvariable = STATUS_BANGUNAN,values=['1. Milik Sendiri','2. Kontrak/Sewa','3. Bebas Sewa','4. Dinas','5. Lainnya'],
                             font=14,state='r',width=33).place(x=320,y=110)

and here is the output

1. Milik Sendiri

but the output i want is 1, so the previous user input is converted to a number.

I have tried using the following code

Status_bangunan.replace({'1. Milik Sendiri':1,'2. Kontrak/Sewa':2,'3. Bebas Sewa':3,'4. Dinas':4,'5. Lainnya':5}, inplace=True)

but it doesn’t work, and here is the error

TypeError: str.replace() takes no keyword arguments

then I also tried the following code

SB = Status_bangunan.replace('1. Milik Sendiri','1')

the result

1

the code works but only for 1 part, what I want is for all of them to be automatically converted not just 1. but str.replace() function only for 2 arguments.

the result that I expect is that when the user inputs through the form (categorical) the results obtained will be automatically converted to numbers

I’m still confused about this, please help.
for the form I use python gui

i have tried this code

Dict1 = {"1. Milik Sendiri":"1", "2. Kontrak/Sewa":"2","3. Bebas Sewa":"3","4. Dinas":"4","5. Lainnya":"5"} 
    for key in Dict1.keys():
        SB = Status_bangunan.replace(key, Dict1[key])

but the result

1. Milik Sendiri
Asked By: Rascalt

||

Answers:

The replace method can only replace strings by strings: 'alpha beta gamma'.replace('bet','delt') == 'alpha delta gamma' Note it’s used to replace part of a string, you wouldn’t use it if you want to change the entire string.

Also, strings are immutable, so a in-place option makes no sense.

You can either do this:

{
    '1. Milik Sendiri': 1,
    '2. Kontrak/Sewa': 2,
    '3. Bebas Sewa': 3,
    '4. Dinas': 4,
    '5. Lainnya': 5
}[Status_bangunan]

This is basically just your second idea but no replace method. There is no need for it.

Another option is to parse the text. This extracts thee part beefore the . then parses it as a integer:

# Parse as integer
int(
   Status_bangunan
       # Split into a list of strings, seperated by a `. `
       .split('. ')
          # Take the first part, which will thus be the part before the .
          [0])
Answered By: mousetail
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.