Trying to sum a sequence of digits from string with characters


#1

Hello all,

Relatively new python user but I used to use c.a. a while back. I need some help with a program and here’s the link to it: https://trinket.io/python/88675e0bbe

I’m outputting concatenated digits over a loop, however I am trying to add these values with two decimal places.

For example If Input “Today I went to the store and bought a pillow for 12.30, a blanket for 4.40 and a toothbrush for 2.25”

I I want the output to be: 18.95 but rather I keep getting 1230440225. Anyone have any Idea what I’m doing wrong?


#2

using + on a string will simply concatenate the string:

print('a' + 'b') # output: ab

same for numbers as string:

print('1' + '2') # output: 12

if you want to add numbers together, you need to integers or floats:

print(1 + 2) #output: 3

so you will need to extract the numbers from the string, convert/cast them to float, and then add them together.


#3

So I guess my issue is that in my program I had to input a sequence of characters (which include a combination of both letters and characters) but then have a loop go through string and pull out only the digit characters, however and then add them based on where some of the numbers were grouped at in the sequence. I don’t know if I explained it well but I posted a link to my code and it might bring what I’m saying into context a little more.


#4

what you say makes perfect sense. So now you know the steps, can you go further? Or do you need more help, if so, what do you need?

you first need to set the boundaries of your program, can you also have integers in the string?

Then i recommend you to hard-code a string and try to extract the digits first