2014-12-04 2 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' 

코드 : 이름을 밖으로 거기에서 random 참조 문자열 객체가 아닌 모듈을

random="" 

:

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

빈 문자열 변수가 포함 된 임의의 모듈을 가리십시오. –

+0

@EricLeschinski : 아니요, 이름은 같은 범위에있는 * 리바운드 *입니다. –

답변

4

당신은 이름 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 –

0

가 :

>>> 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' 

당신은에 의해 잘 중독 무작위 모듈을 string 유형으로 다시 정의합니다. 그런 다음 문자열에 randrange 메소드를 호출했습니다. 그리고 그것은 문자열 객체가 가지고 있지 않다는 것을 알려줍니다.

+0

고맙습니다. –

관련 문제