简体   繁体   中英

Converting string to integer Python

I am trying to count the number of 0's, positives, negative numbers in array. I have explicitly converted every string to integer here:

k = []
n = int(raw_input())
p=neg=z=0
p = int(p)
neg = int(neg)
z = int(z)

for i in range (0,n):
    numb = int(raw_input("numb: "))
    if numb==0:
        z +=1
    if numb<0:
        neg+=1
    if numb>0:
        p +=1
    k.append(numb)

print "Array: ", k
print '%.5f' %z/n
print '%.5f' % neg/n
print '%.5f' %p/n

It keeps giving me this error: unsupported operand type(s) for /: 'str' and 'int'.

You need to add parens:

print "Array: ", k
print '%.5f' % (z / n)
print '%.5f' % (neg / n)
print '%.5f' % (p / n)

The format is being done first so you end up trying to / the result which is a string by an int. The parens will mean the division etc.. is done and the result is formatted.

You might find using str.format less error prone:

print '{:.5f}'.format(z / n)

Also unless you want the division to floor you should cast to float not int:

n = float(raw_input())

Quoting official documentation :

The following table summarizes the operator precedences in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left).

While studying table we can see row:

*, /, //, % Multiplication, division, remainder [8]

Footnote [8] says:

The % operator is also used for string formatting; the same precedence applies.

Both % and / operators has same precedence. Therefore - they are evaluated in standard order. Following equality holds:

'%.5f' %z/n == (`%.5f` % z) / n

To change evaluation precedence you need to use parentheses.

'%.5f' % (z/n)  # It would format string with a result of z/n operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM