所以,我开始在codecademy学习Python,我正在尝试创建一个程序,你可以在其中输入一个单词并为它加扰它。但是,我很难找到如何去做。这就是我到目前为止所拥有的。
#Scrambler is a game that will take a given word and scramble it
print ("Welcome to Scrambler!")
word = input("Enter a word:")
if len(word) > 0 and word.isalpha():
print (random.shuffle (word))
elif word.isalpha == False:
print ("Sorry, please try again")
else:
print ("Sorry, please try again")
*它说“随机”没有定义,但我在Python中查找了命令,并说random.shuffle()是一个内置函数。
答案 0 :(得分:1)
random是Python标准库中包含的模块,但您仍需要使用'import'语句来访问它的函数。
另外random.shuffle()仅适用于iterables,不适用于字符串。然而,你可以将单词拆分成一个列表,将其洗牌,然后将其重新加入。
import random
print ("Welcome to Scrambler!")
word = input("Enter a word:")
if len(word) > 0 and word.isalpha():
letters = [i for i in word]
random.shuffle(letters)
print (''.join(letters))
elif word.isalpha == False:
print ("Sorry, please try again")
else:
print ("Sorry, please try again")
答案 1 :(得分:1)
你需要:
结果将是:
import random
#Scrambler is a game that will take a given word and scramble it
print ("Welcome to Scrambler!")
word = input("Enter a word:")
if len(word) > 0 and word.isalpha():
wordaslist = list(word)
random.shuffle(wordaslist)
print (''.join(wordaslist))
elif word.isalpha() == False:
print ("Sorry, please try again")
else:
print ("Sorry, please try again")