Python 类型错误:一元的错误操作数类型 -:'str'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15845241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:09:19  来源:igfitidea点击:

TypeError: bad operand type for unary -: 'str'

pythonstringpython-2.7typeerror

提问by Fleisis

I've got a problem with Python 2.7.3-32bits on Windows. I put this code to see if anyone can help me out with this error. The comments are in Spanish but it don't affect the code.

我在 Windows 上遇到了 Python 2.7.3-32bits 的问题。我把这个代码放在看看是否有人可以帮助我解决这个错误。注释是西班牙语,但不影响代码。

 import gtk
 import numpy
 import math
 import os

 #Pedimos el nombre de la imagen de origen
 nombreFich = input("Por favor, introduzca el nombre de la imagen de origen:")

 #Validar que existe el fichero
 imagen1 = gtk.Image()
 imagen1.set_from_file('C:\Users\xxx\Desktop\xxxx.png')
 pb1 = imagen1.get_pixbuf()
 pm1 = pb1.get_pixels_array()

 #Hacemos una copia de la imagen
 pm2 = pm1.copy()

 #Validamos los puntos de distorsion hasta que sean validos
 puntos = " "
 arrayPuntos = " "
 while(puntos == " " and len(arrayPuntos) < 4):
     print"Por favor, introduzca los puntos de distorsión xc yc r e:"
     puntos= raw_input()
     arrayPuntos = puntos.split(" ")

 #Sacamos los puntos separando la cadena por el caracter espacio
 xc =(puntos[0])
 yc =(puntos[1])
 r =(puntos[2])
 e =(puntos[3])

 #función que calcula el grado de distorsión
 def grado(self,z,e): 
     if(z>1):
         return 1
     elif(e<0):
         return (1/z)**(-e/(1-e))
     else:
        return z**e

 #Distorsionamos la imagen
 def distors(xc,yc,r,e,x,y):
     d = math.sqrt(x**2+y**2)#Sacamos la distancia
     z = d/r
     if(z!=0):
         g=grado(z,e)
         xm=x*g
         ym=y*g
         return xm,ym

     else:
         xm=x
         ym=y
         return xm,ym
 def recorrido (pm1, xc, yc, r, e):
     pm2 = pm1.copy()

     x= str(--r)
     y= str(--r)
     while (y <= r):                     
         while (x <= r):
             xm, ym = mover(xc, yc, r, e, x, y)
             pm2[yc+y][xc+x] = pm1[yc+ym][xc+xm]
             x = x+1
         y= y+1
         x= -r


     return pm2
 pm2 = recorrido(pm1, xc, yc, r, e)

 #Guardamos los cambios
 pb2 = gtk.gdk.pixbuf_new_from_array(pm2,pb1.get_colorspace(),pb1.get_bits_per_sample())
 nomfich2 = nombreFich+"_copia"
 ext = os.path.splitext("C:\Users\xxx\Desktop\xxxx.png_copia")[1][1:].lower()
 pb2.save("C:\Users\xxx\Desktop\xxxx.png_copia",ext)
 print"FINISH"

When I run the python code I get the following error:

当我运行 python 代码时,出现以下错误:

 Traceback (most recent call last):
   File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 71, in <module>
     pm2 = recorrido(pm1, xc, yc, r, e)
   File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 59, in recorrido
     x= str(--r)
 TypeError: bad operand type for unary -: 'str'

采纳答案by abarnert

The error message is telling you that ris a string. You can't negate a string.

错误消息告诉您这r是一个字符串。你不能否定一个字符串。

Why is it a string? Well, it seems to come from here:

为什么是字符串?好吧,它似乎来自这里:

# ...
puntos= raw_input()
arrayPuntos = puntos.split(" ")
# ...
r =(puntos[2])

The splitmethod on a string returns a list of strings.

split字符串上的方法返回一个字符串列表。

So, how do you solve this? Well, if ris, say, the string "22", then float(r)is the float 22.0, and int(r)is the integer 22. One of those is probably what you want.

那么,你如何解决这个问题?好吧,如果r是,比如说,字符串“22”,那么float(r)是 float 22.0int(r)是 integer 22。其中之一可能就是您想要的。

Once you add, say, r=int(r), your --rwill no longer be an exception.

一旦您添加,例如,r=int(r)--r将不再是例外。



But it probably isn't what you want. In Python, --rjust means the negation of the negation of r—in other words, it's the same as -(-(r)), which is just r. You're probably looking for the equivalent of the C prefix operator--, which decrements the variable and returns the new value. There is no such operator in Python; in fact, there are no operators that modify a variable and then return the value.

但这可能不是你想要的。在 Python 中,--rjust 表示否定的否定r——换句话说,它与 相同-(-(r)),也就是r。您可能正在寻找 C 前缀 operator 的等效项--,它减少变量并返回新值。Python 中没有这样的操作符;事实上,没有操作符可以修改变量然后返回值。

This is part of a larger issue. Python is designed to make statements and expressions as distinct as possible, to avoid confusion. C is designed to make as many things as possible expressions, to save typing. So, you often can't just translate one into the other line by line.

这是一个更大问题的一部分。Python 旨在使语句和表达式尽可能不同,以避免混淆。C 旨在制作尽可能多的表达式,以节省输入。因此,您通常不能将一行一行地翻译成另一行。

In this case, you have to do it in two steps, as Thanasis Petsas shows:

在这种情况下,您必须分两步完成,如 Thanasis Petsas 所示:

r -= 1
x = str(r)

回答by Thanasis Petsas

Increment ++and decrement --operators are not supported in python. You can use instead this:

Python 不支持自增++和自减--运算符。你可以使用这个:

r -= 1
x = str(r)