0

I have a function that looks like this:

def test(in1):

  if in2 = 151:
    print('error')


  if in2 == 1:
    in1 = 14
    print(in1)

The function currently takes in a string value,

I was thinking:

if in2 == 'one':
   in2 = 14

But that doesn't work for some reason

Thanks

jackiegirl89
  • 87
  • 1
  • 9
  • But you aren’t testing to see if the value of the string is `'one'`? Also to test if `int` use `isinstance(in2, int)` – SuperShoot Mar 29 '19 at 23:45
  • see reply below...you don't need to convert 'one' to 1, you can just directly assign the value 1 to your variable.. – dvitsios Mar 29 '19 at 23:47
  • @jackiegirl89 you'll have to write a dict to do that. I can't think of any other way than have a dict with key being the string and value being the int. Assuming what you want is to be able to convert written numbers to integers. – Vulpex Mar 29 '19 at 23:47
  • 1
    @SuperShoot: Thanks for finding this. The only duplicates I recalled were in Java and C++; I couldn't find this one. – Prune Mar 29 '19 at 23:56

4 Answers4

0

Do you just want the following?

if in2 == 'one':
    in2 = 1
dvitsios
  • 458
  • 2
  • 7
0

You're trying to convert 'one' to an integer which won't work because python doesn't know that the word one refers to the integer 1. What you need to do is put in2 = 1 in the body of your if-statement.

if in2 == 'one':
       in2 = 1
Nathan Hamm
  • 300
  • 1
  • 4
0

It doesn't work because the int conversion works only on the string image of an integer numeral. int("1") would work.

Python does not have a built-in function to convert text strings to numbers. You will need to provide that with some sort of conversion function of your own. In the restricted example you gave, it's simply a matter of

if in2 = "one":
    in2 = 1

However, you seem to want a more general solution. There are programs you can look up for converting number phrases to integers in general. For now, you may want simply a look-up table; a dict works well for this.

str_to_int = {
      "one": 1, "two": 2, "three":3,      # Continue as far as you need
    }

Now, you can do something such as

if in2 in str_to_int:
    in2 = str_to_int[in2]

This is still awkward programming, as it does very little for error cases, and you've used one variable for two distinct purposes -- neither of which is apparent from its name. However, fixing all of those problems would involve an overhaul, better done on your own time.

Prune
  • 76,765
  • 14
  • 60
  • 81
-1
num_str = ["one", "two", "three", "four", "five"]
num_int = [1, 2, 3, 4, 5]
if(in2 in num_str):
    foo = num_str.index(in2)
    output = num_int[foo]
    return output

This should work because you have a pre-defined list of numbers but spelled out. If your function parameter is equal to a string in this list, it will get the according integer from the list of numbers in integer form and return it.

Ryan Wans
  • 28
  • 5