newbie question int to string conversion
prestonlanders at my-deja.com
prestonlanders at my-deja.com
Mon Oct 4 12:27:23 EDT 1999
Anders,
This might be what you want. you can change the line new_item = None
to change the value for exceptional items. and/or you can change the
if: line to raise an exception for a bad value, your choice. My way is
more efficient but puts off dealing with exceptional items until
later.
hope this helps.
yours,
---Preston
import re
mylist = ["1", "2", "3f", "foo", "4"]
def string_list_to_int_list(string_list):
return_list = []
for item in string_list:
new_item = None # default value for invalid items
if not re.search("\D", item):
new_item = int(item)
return_list.append(new_item)
return return_list
print "Original list was %s" % repr(mylist)
print "Converted list is %s" % repr(string_list_to_int_list(mylist))
In article <m3emfegwg3.fsf at localhost.localdomain>,
Anders olme <olme at ebox.tninet.se> wrote:
> Hello.
>
> I'm tryinig to convert a list of strings to integer.
> The problem is that not all elements are numbers some of them
contains letters
> Is there any easy way to determine is a strings contains illegal
charaters?
> Now I only get exceptions and I think a exceptionshandler is a bit
overkill
> for my needs.
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list