我试着这样做:你输入一个这样的词:快乐而且程序会返回像yppaH或appHy这样的东西.
问题是我只得到一个字母:y或H等.
import random
def myfunction():
"""change letter's position"""
words = input("writte one word of your choice? : ")
words = random.choice(words)
print('E-G says : '+ words)
Run Code Online (Sandbox Code Playgroud)
你必须使用sample,而不是choice.
import random
# it is better to have imports at the beginning of your file
def myfunction():
"""change letter's position"""
word = input("writte one word of your choice? : ")
new_letters = random.sample(word, len(word))
# random.sample make a random sample (without returns)
# we use len(word) as length of the sample
# so effectively obtain shuffled letters
# new_letters is a list, so we have to use "".join
print('E-G says : '+ "".join(new_letters))
Run Code Online (Sandbox Code Playgroud)
用于random.shuffle转换列表中的字符串(就地工作)
然后使用转换回字符串 str.join
import random
s = "Happy"
sl = list(s)
random.shuffle(sl)
print("".join(sl))
Run Code Online (Sandbox Code Playgroud)
输出:
pyapH
Hpayp
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61 次 |
| 最近记录: |