Do I need to convert string to integer in python?

Discussion in 'Python' started by Allerdyce.John, Feb 26, 2006.

  1. Do I need to convert string to integer in python? or it will do it for
    me (since dynamic type)?

    In my python script, I have this line:
    x /= 10;

    when i run it, I get this error:
    TypeError: unsupported operand type(s) for /=: 'unicode' and 'int'

    I want to divide x by 10 and assign that value back to x.

    Thank you.
     
    Allerdyce.John, Feb 26, 2006
    #1
    1. Advertisements

  2. Yes. Dynamic typing doesn't say anything about a string and a number being
    "equal," as they are (e.g.) in Perl, it just says that you don't have to
    care what type of object a name is bound to. What you are thinking of is
    called weak typing (auto-coercion between strings and numbers and such).

    You'd have to do something like:
    x = int(x)/10

    --- Heiko.
     
    Heiko Wundram, Feb 26, 2006
    #2
    1. Advertisements

  3. Nope, no such implicit conversion (thanks be!). Strings are strings and
    ints and ints and never the twain shall meet, except by explicit
    request;-).

    If you want x to remain a Unicode string when you're done,

    x = unicode(int(x) / 10)

    should work. If you want x to become an integer, omit the unicode call
    around the int(x)/10 expression.


    Alex
     
    Alex Martelli, Feb 26, 2006
    #3
  4. Yes, you have to convert beforehand. Dynamic typing and weak typing (as in perl or php) aren't the same thing.

    Dynamic typing means that you can rebind a variable (or better name) at runtime to contain a value with a new type. Weak
    typing means that an object is reinterpreted as a value of another type when needed - and (often) leads to difficult errors.


    Regards,

    Diez
     
    Diez B. Roggisch, Feb 26, 2006
    #4
  5. Traceback (most recent call last):
    File "<pyshell#4>", line 1, in -toplevel-
    x/=10
    TypeError: unsupported operand type(s) for /=: 'str' and 'int'10

    Michael
     
    Michael Amrhein, Feb 26, 2006
    #5
  6. No, the Python interpreter is playing a practical joke on you when it
    raises that exception. Just persevere with the x /= 10 line, and
    eventually the interpreter will give in and give you the result you need.
    But be warned, if it is in a particularly playful mood, you may need to
    try hundreds of times before it will stop messing about and get back to
    work.

    By the way, semi-colons are not required at the end of lines in Python.
     
    Steven D'Aprano, Feb 26, 2006
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.