[Tutor] Changing only intergers in a list of strings
David Palao
dpalao.python at gmail.com
Wed Feb 5 11:47:32 CET 2014
Sorry, there is a typo:
"(num+a,)" should be "(num+1,)", obviously.
2014-02-05 David Palao <dpalao.python at gmail.com>:
> Hi,
> Is it not clear to me if you must distinguish ints from other type of
> numbers, or if, for instances floats and ints must be dealt
> differently.
> Anyway, I would propose something like the following function:
>
> def FindNumbers(a_string):
> print "You entered:", a_string
> out_list = []
> for item in a_string.split():
> try:
> num = int(item)
> except ValueError:
> out_list.append(item)
> else:
> out_list.append("%s" % (num+a,))
> out_string = ' '.join(out_list)
> # do whatever you want to do with the resulting out_string:
> return it, or display it...
>
> Some comments:
> 1) I would pass the input string as argument rather than using it as a global.
> 2) You could use float instead of int to make it more general
> 3) If you need to distinguish between ints and floats, then you must
> add a couple of extra lines
>
> I hope it helps.
>
> Best
>
>
> 2014-02-04 Colin Struthers <303cookiemonster at gmail.com>:
>> I am in a beginning python course and am working through some code and I
>> can't even figure out how to start building this particular section of code.
>>
>> My goal is to get a sentence for the user and to take each number in the
>> user string and add 1 to each number. i.e "the 4 people had 6 dogs" would
>> change to "the 5 people had 7 dogs"
>>
>> a_string = [ ]
>> int_list = [ ]
>> a_string = raw_input("Enter a sentence with both words and numbers: ")
>>
>> def FindNumbers():
>> print "You entered: ", a_string
>> for ints in a_string
>> ...?
>>
>> FindNumbers()
>>
>> I fully understand that this doesn't even begin to work but I don't really
>> know where to start deconstructing the list, editing only the intergers, and
>> joining it all back together.
>>
>> Thanks for the help.
>>
>> --
>> Colin
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
More information about the Tutor
mailing list