[Tutor] string to integer

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Jan 5 22:02:03 CET 2006


On Thu, 5 Jan 2006, Boyan R. wrote:

> I need program to convert my string in integer.
> I remember in BASIC I used  val(string) command
> Is there a Python equivalent ?
>
> Here is how it should work:
> val(7) = 7
> val(bbab7) = 7
> val(aa7aa) = 7
> val(   7) = 7


Hi Boyan,

Python has a function that's somewhat similar called the int() function.

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-39


However, it's a bit more strict about its input than what you may be used
to:

######
>>> int("   5")
5
>>> int("5th")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 5th
######


To make something like val, we can try to pull out the first bunch of
digits we see, and int()ify that.  Here's one example of this approach:

###############################################################
import re

def val(s):
    """Tries to extract the first integer value we can see from
    string s."""
    result = re.search(r"\d+", s)
    if not result:
        raise ValueError, ("invalid literal for val(): %s" % s)
    return int(result.group(0))
###############################################################


Let's see how this works:

######
>>> val("5th")
5
>>> val("this is 1derful")
1
>>> val("huh?")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in val
ValueError: invalid literal for val(): huh?
######



> Also, what are chr() values for enter and (empty) space ? If anybody
> have a table with chr() values, I'd appreciate if he upload it
> somewhere. Thanks in advance !

I think you're asking: what's the ordinal values that we input into
chr() to get the enter and space characters?

If so: do you know about the ord()  builtin function?

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-53

Play around with it, and I think you should be able to get the values you
are looking for.


If you have more questions, please feel free to ask.



More information about the Tutor mailing list