[Tutor] string to integer

Alan Gauld alan.gauld at freenet.co.uk
Thu Jan 5 23:16:44 CET 2006

> Here is how it should work:
> val(7) = 7
> val(bbab7) = 7
> val(aa7aa) = 7
> val(   7) = 7  

There is no direct equivalent for val() as shpwn above the 
nearest is int() or float() but that will only work with the first
and last examples. (It is a pretty arbitrary functionn  to convert 
aa7aa to 7!)
What does val do with a6b5c?

You could strip all chars out of the string first:

nums = [ch for ch in aString if ch in string.digits]
val = int(str(nums))

Which would result in 65 for the example I gave... and 
that might be what you expect?

> This last is most important, currently I don't know how to
> convert string "   7" to integer value 7 in my program

Just use int()

> Also, what are chr() values for enter and (empty) space ?

Why would you need chr if you know its an empty space? 
Just use ' ' directly. 

if ch = ' ':....

'enter' is more tricky since it depends on your OS and to 
some extent your terminal type. For example a TekTronics 
terminal in an xterm window on Linux gives a different value 
for Enter than the default vt100 terminal...

Again, if we knew why you needed to know we might be able 
to suggest a suitable mechanism otr alternate technique?

> If anybody have a table with chr() values, I'd appreciate
> if he upload it somewhere. 

Just do a google search for ASCII that should find several 
tables of the value/character combinations. Searching for 
Unicode will likewise find the Unicode values.

chr() is just the string representation of a number.

n = ord(c)
print chr(ord(c))

should print c since ord() convers the character to a number 
and chr() converts it back...

for n in range(256): print chr(n)

will print all of them (although some are unprintable!)


Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list