K
K
KeterVik2018-05-22 19:55:35
Python
KeterVik, 2018-05-22 19:55:35

How to properly convert a string to a number?

There is a list of the form: I create a function:
array = ["one", "two", "three"]

def func(arg):
    if arg == "one":
        return 1
    elif arg ...
to convert a string to a number.
After that I write:
var = random.choice(array)
new_array = []
new_array.append(func(var))
, but the values ​​in the list are always [1, 1, 1, ...]. One units. I assume that the function entry that changes the string value to an integer is incorrect. How to write it down correctly? There are dozens of elements in my source code. The bottom line is that they are all string literals. But each of them must have a numeric value, for this I need to convert each string literal to a number. That is, I need to create a function so that a random string literal is converted to a number.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-05-22
@KeterVik

Instead of a diaper of if's, it is much easier and more efficient to use an index in the list if the elements in the list are the following numerals in order:

NUMERALS = [
    'zero',
    'one',
    'two',
    ...
]

def numeral2number(numeral):
    return NUMERALS.index(numeral.lower)

And if not in order, then a dictionary
NUMERALS = {
    'zero': 0, 
    'one': 1,
    'two': 2,
    ...
}

def numeral2number(numeral):
    return NUMERALS.get(numeral.lower)

A
Alexander, 2018-05-22
@kentuck1213

code.activestate.com/recipes/578258-spoken-word-to...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question