在python中导致此错误的原因是什么?
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)
答案 0 :(得分: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
答案 1 :(得分: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。而且它告诉你字符串对象没有它。