hi everybody!!!
I will really appreciate if somebody could help me....
we are working with c and python and the same time and it gets confusing sometimes...

I need to write a program in python tha will receive a string and it will print only the number in the string and the sum of them...

An example of what it should print...

input: 80,45,34
print: 80+ 45+ 34= 159

input: i have 2 bananas and 3 oranges
print: 1+2+3= 6

this is what i got...

data=""
indice=0
number=""
x=0
y= 2
data = input("Please enter a string\n")
print len(data)
while indice < len(data):
        if (data[x]<57 and data[x]>48):
            print ("%s", data [x])
            count += (int(data[x])) + count
            x +=1
            y -=1
            indice +=1
        elif (data[x]>57 and data[x]<48):
            if w!=1:
                w=1
                x +=1
                print ("+")
                indice +=1
            elif w==1:
                w=0
                indice +=1
else:
    print ("=%d", count)

pleasee help!!!!!!!....

Recommended Answers

All 8 Replies

I don't think I understand the second example...

input: i have 2 bananas and 3 oranges
print: 1+2+3= 6

Where'd the 1 come from?

Code comments:

line 6:

data = input("Please enter a string\n")

Should use raw_input to get string data.

You appear to be dividing the characters up based on whether or not they are digits, seems like a sound idea. Where are you building the multi-digit numbers?

Where are you building the sum of the numbers you've found?

You can iterate all of the characters in a string and only output the digits with something like:

digits = "0123456789"
for x in data:
    if x in digits:
        print x

I don't know if that make your problem any easier, but I find it easier to read and understand.

This statement will never be true
elif (data[x]>57 and data[x]<48):

Hint, another approach would be to use the function split() ...

text1 = "80,45,34"
if "," in text1:
    # split at comma
    mylist1 = text1.split(",")
    print( mylist1 )  # ['80', '45', '34']

text2 = "2 bananas and 3 oranges"
if " " in text2:
    # split at space
    mylist2 = text2.split(" ")
    print( mylist2 )  # ['2', 'bananas', 'and', '3', 'oranges']

# extract numbers from a list
for item in mylist2:
    if item.isdigit():
        number = int(item)
        print number  # test -->  2  3

Thats a bit of a complicated code for a sum. If you want a program that adds three numbers up do it like this:

number_one = input("What is your first number?")
number_two = input("What is your second number?")
number_three = input("What is your third number?")

print number_one + number_two + number_three


This will display the answer in the window.

This is how I got it to work:

def pullNumbers(data):
    NumData, total, x_full = ([], 0, "")
    
    for x in data:
        try:
            int(x)
            x_full = x_full + x
        except:
            if x_full is not "":
                NumData.append(x_full)
            x_full = ""
    if x_full is not "":
        NumData.append(x_full)
    OutNumData = " + ".join(NumData)
    for s in NumData:
        total = total + int(s)
    print "%s = %d" % (OutNumData, total)


pullNumbers(raw_input('Enter a string with some random ints in it'))

I call the function with the text string containing some numbers, if the user put some in (for example: "Give me 4 eggs and I will make 1 cake for all 11 of you" will give you "4 + 1 + 11 = 16")

First set the variables.
Then the for loop divides everything up into strings of length 1, and we try to see if we can get an int out of each one.

the x_full variable is there to catch numbers longer than 10. We only add to the list (NumData) in the except block because it would have gone on to the next non number string. This helps us get numbers larger than 10.

Perhaps this is sloppy, but I had to put the 'if x_full...' line in a second time, after the 'for' block, just in case the very last thing in the input was a number (meaning the except block wouldn't have been run, and the number never added to the list NumData.)

Once we have the list, getting the values out is easy. Just remember you can't add a string to an in, and therefor this format is more useful.

Just a note, one of the reasons to break it down to individual strings, rather than using split(' ') kind of thing is that we would have had trouble if in the input was "1, 2, 3", where as now that works fine.

Thank u all so much!!!, you guys are amazing!!!
Im going to try out every thing you guys send!!! will let u knoww!!!!

Thanx again!!!!!!

Hi, you are simply amazing! and you just save my life!

would you like to explain me just the codes that u used? like what do every one??, Thanx again!!!!....

ps.. I have to do like 5 other things in c, they are done, but im still getting a few mistake... would you like to see them and help me arrange them?

I would really appreciate all your help!!

How Can I thank you????

thanxxx

This is how I got it to work:

def pullNumbers(data):
    NumData, total, x_full = ([], 0, "")
    
    for x in data:
        try:
            int(x)
            x_full = x_full + x
        except:
            if x_full is not "":
                NumData.append(x_full)
            x_full = ""
    if x_full is not "":
        NumData.append(x_full)
    OutNumData = " + ".join(NumData)
    for s in NumData:
        total = total + int(s)
    print "%s = %d" % (OutNumData, total)


pullNumbers(raw_input('Enter a string with some random ints in it'))

I call the function with the text string containing some numbers, if the user put some in (for example: "Give me 4 eggs and I will make 1 cake for all 11 of you" will give you "4 + 1 + 11 = 16")

First set the variables.
Then the for loop divides everything up into strings of length 1, and we try to see if we can get an int out of each one.

the x_full variable is there to catch numbers longer than 10. We only add to the list (NumData) in the except block because it would have gone on to the next non number string. This helps us get numbers larger than 10.

Perhaps this is sloppy, but I had to put the 'if x_full...' line in a second time, after the 'for' block, just in case the very last thing in the input was a number (meaning the except block wouldn't have been run, and the number never added to the list NumData.)

Once we have the list, getting the values out is easy. Just remember you can't add a string to an in, and therefor this format is more useful.

Just a note, one of the reasons to break it down to individual strings, rather than using split(' ') kind of thing is that we would have had trouble if in the input was "1, 2, 3", where as now that works fine.

Okay, I thought that I did explain my code - did you read what I wrote afterwards?

In case you really are just a beginner, here it is again with heavy comments:

#! /usr/bin/python

# sandbox.py

def pullNumbers(data):
    """A function that will pull random numbers out of a string,
    
    and add them together"""

    # First we set some variables that we will use in the function
    # In Python you can set a bunch of stuff together like this
    # It isn't beautiful (which Python should be) but it is clean
    # NumData becomes an empty list.  This means we can append to it.
    # total is an int of value 0.  It is the number we will add to for our total
    # x_full is an empty string.  We will be adding to it each time we get a number
    NumData, total, x_full = ([], 0, "")
    
    # for x in data loops through the 'data' variable
    # Each time round the loop, x takes the next value of a character of the data string
    # These characters include spaces and the number strings. (i.e. '1' is a string)
    for x in data:

        # I am sure you can do it with if statements
        # I just thought it was easier this way.
        # The reason for the try, excpet blocks is that int(x) is basically trying to
        # create an int representation of the string.
        # If it was not a number (0-9), Python will throw up an error.
        # The try, except catches the errors
        try:
            int(x) # If between 0 and 9 the block continues, otherwise the error exits the block
            # So now we know that x is a number between 0 and 9
            # So we add it to x_full (as a string, not an int...you will see why below
            # As long as x remains a 0-9 value, we keep adding to x_full
            # eg 123 will go round three times x_full will be '1', then '12', then '123'
            x_full = x_full + x
        # Now, if x was not a 0-9 value, we catch the error here

        except:
            # if x_full is "" we don't want to add it
            # otherwise NumData will give us an error (trying to add strings to ints)
            # Python don't like that
            if x_full is not "":

                # If it is not "", we know that it must have passed through the try
                # and added one or more 0-9 values
                # So we add it to the list, NumData for later use.
                # NumData goes from being [] to ['23'] then ['23', '2'] etc...
                # I hope it is clear why we do it here and not in the try block -
                # If we added it up there, when we had a number like 34
                # x would be '3' and it would be added to NumData ['3']
                # then x would be '4', added to x_full and added to NumData
                # we would get ['3', '34'] - not what we want
                NumData.append(x_full)

            # So we know we came to then end of a number, so we re-set x_full
            # to an empty string.
            x_full = ""

    # So we have one small problem
    # What if our last value was a number, for example"
    # "Here are 2 and there are 34"
    # The try section would get 34 added
    if x_full is not "":
        NumData.append(x_full)
        # We don't need to worry about clearing x_full, we are done with it.

    # Here is the easy part now.  We make a string OutNumData
    # By taking all the peaces of NumData and joining them with a space+space string
    # for example if NumData was ['1', '23', '44']
    # OutNumData becomes "1 + 23 + 44" - now you see why we kept the NumData values as strings
    OutNumData = " + ".join(NumData)

    # We are not done with NumData, we still need to do the addition
    # s becomes the string value of each string in NumData
    for s in NumData:
  
        # Remember total right from the beginning, which we set to 0
        # So total is an int, and we can add to it with other ints
        # Till now our values in NumData have remained strings
        # So we ask Python nicely for the int representation of s
        # For a Python student, not that s cannot be turned into an int
        # We can only get the represenation of it as an output.
        # Python is strongly typed, even though it is dynamically typed.

        # So after we run through the for loop, we have the numbers added up in total
        total = total + int(s)

    # Just to get some output, we print to the command line
    # OutNumData is a string, something like this: "1 + 29 + 29930"
    # total is an int, in the case of the above numbers, 29960
    # You can't add a string and an int, so we join them like this
    # With space=space between them
    print "%s = %d" % (OutNumData, total)
    # Ouput something like this:
    # '1 + 29 + 29930 = 29960'

# Here we call the function, created above
# The function, pullNumbers, takes one value, so we pass it a value
# We just cheat a bit, and do the raw_input call within the function call
# It is the same as doing this:
# x = raw_input("Give us your string, we'll take your numbers\n--> ")
# And then calling the function:
# pullNumbers(x)
pullNumbers(raw_input('Enter a string with some random ints in it\n-->'))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.