Michal Škultéty
Michal Škultéty

Reputation: 228

saving the number into the variable in every run of cycle python

I wrote the function that converts the string in argument to number. If the string does not contain number the cycle breaks and the new variable with numbers is printed. If the argument is "123" the function returns 6. I don't want to return the sum, just placing every number in a row. How do I accomplish the result 123? I don!t know what to use instead of string2 += float(c).

def try_parse(string):
 string2=0
 for c in string:
  if c.isdigit() == True: 
   string2 += float(c)
  else:
    break 
 return string2

Upvotes: 1

Views: 196

Answers (3)

Or Duan
Or Duan

Reputation: 13850

I modified your code:

def try_parse(string):
    string2 = ""
    for c in string:
        if not c.isdigit() and c != '.':
            break
        string2 += c
    return string2

You can see that now I use string2 as a string and not an int (When the + sign is used on an int you sum, and with a string + is used for concatenation).

Also, I used a more readable if condition.


Update:

Now the condition is ignoring the '.'.

Tests:

>>> try_parse('123')
'123'
>>> try_parse('12n3')
'12'
>>> try_parse('')
''
>>> try_parse('4.13n3')
'4.13'


Note

The return type is string you can use the float() function wherever you like :)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1123650

You could leave the conversion to a number to Python (using int(), rather than float(); you only filter on digits), and only worry about filtering:

def try_parse(string):
    digits = []
    for c in string:
        if c.isdigit():
            digits.append(c)
    return int(''.join(digits))

but if you really want to build a number yourself, you need to take into account that digits are not just their face value. 1 in 123 does not have the value of one. It has a value of 100.

The easiest way then to build your number would be to multiply the number you have so far by 10 before adding the next digit. That way 1 stays 1, and 12 starts as 1 then becomes 10 as you add the 2, etc:

def try_parse(string):
    result = 0
    for c in string:
        if c.isdigit():
            result = result * 10 + int(c)
    return result

Upvotes: 0

rlms
rlms

Reputation: 11060

You need to use a string for string2, and str instead of float.

You want string2 = "", and string2 += c. (You don't need to call str on c because it is already a string.)

Upvotes: 0

Related Questions