Answer the question
In order to leave comments, you need to log in
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. 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
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)
NUMERALS = {
'zero': 0,
'one': 1,
'two': 2,
...
}
def numeral2number(numeral):
return NUMERALS.get(numeral.lower)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question