2014-12-04 39 views
0

在python中导致这个错误的原因是什么?Python错误'str'对象没有属性'randrange'

Traceback (most recent call last): 
    File "F:/coding/python/python programming for absolute beginners/chapter 4/ 
    The Jumble Game.py", line 9, in <module> 
    p=random.randrange(len(word)) 
AttributeError: 'str' object has no attribute 'randrange' 

代码:

import random 
print"\t\t\tThe Jumble Game" 
print"In this program you will be given a jumble word and you have to guess that word" 
set=("book","parrot","rabbit") 
word=random.choice(set) 
random="" 
jumble="" 
while(word): 
    p=random.randrange(len(word)) 
    random=random+word[position] 
    word=word[:position]+word[(position+1):] 
print("The jumble word is",random) 
+2

你使用空字符串变量遮盖随机模块。 – 2014-12-04 16:45:08

+0

@EricLeschinski:不,名称在相同的范围内只是*反弹*。 – 2014-12-04 16:52:39

回答

4

您重用名称random

random="" 

从那里出来,这个名字random引用一个字符串对象,而不是模块。重命名该变量不会影响您导入的模块。

要洗牌了一个字,它会更容易使用random.shuffle()代替:

word = random.choice(set) 
letters = list(word) 
random.shuffle(letters) 
jumbled_word = ''.join(letters) 
print "The jumble word is", jumbled_word 
+0

谢谢#Martijn Pieters – 2014-12-04 16:50:15

0

如何重现此错误在Python解释:

>>> import random 
>>> type(random) 
<type 'module'> 
>>> random.randrange(2) 
1 
>>> random.randrange(2) 
0 
>>> random = "" 
>>> type(random) 
<type 'str'> 

>>> random.randrange(2) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'str' object has no attribute 'randrange' 

您可以通过毒害井将随机模块重新定义为字符串类型。然后你调用一个字符串的randrange方法。它告诉你字符串对象没有它。

+0

非常感谢 – 2014-12-05 12:04:51

相关问题