在写程序时遇到了这么一个问题,代码如下:
def gen():
s=''
n = np.random.randint(0, 3)
print(n)
if n==0:
s=s+'('+random.choice(digits)+random.choice(opr)
+random.choice(digits)+')'+random.choice(opr)+random.choice(digits)
elif n==1:
s=s+random.choice(digits)+random.choice(opr)+'('
+random.choice(digits)+random.choice(opr)+random.choice(digits)+')'
elif n==2:
s=s+random.choice(digits)+random.choice(opr)
+random.choice(digits)+random.choice(opr)+random.choice(digits)
return s
gen()
分开一步步粘贴出来运行是没问题的,可是运行这个函数就报错;TypeError: bad operand type for unary +: 'str'
在Stack Overflow上找到了一种解释,链接如下:https://stackoverflow.com/questions/29880136/python-2-7-typeerror-bad-operand-type-for-unary-str
大意就是这个没有把一元运算符做字符串,可以通过给右边式子加上括号来解决,修改后的代码如下:
def gen():
s=''
n = np.random.randint(0, 3)
print(n)
if n==0:
s=(s+'('+random.choice(digits)+random.choice(opr)
+random.choice(digits)+')'+random.choice(opr)+random.choice(digits))
elif n==1:
s=(s+random.choice(digits)+random.choice(opr)+'('
+random.choice(digits)+random.choice(opr)+random.choice(digits)+')')
elif n==2:
s=(s+random.choice(digits)+random.choice(opr)
+random.choice(digits)+random.choice(opr)+random.choice(digits))
return s
gen()