[Tutor] Adding numbers within a string

Alan Gauld alan.gauld at yahoo.co.uk
Wed Oct 12 04:25:09 EDT 2016


On 12/10/16 01:37, LQ Soh wrote:
> To whom it may concern,
> Can someone enlighten me as to how you can create a function such
> that sum_numbers('10 5 8'), when run, will give an answer of 23, without
> using str.split() and using a for loop

I'm assuming this is some kind of classroom exercise?
Otherwise the advice is just use string split()!

If it is a class  exercise then the easiest option
is to write your own string split(). That is a
function that takes in a string and spits out
substrings. To do that you need to traverse the
string and look for separators. Store the characters
between separators in a list. return the list.

Another way to do it is to use a regular expression
to detect the groups of characters - do you know
about regex?

Once you have done the splitting you need to
convert the substrings into numbers and add
them.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list