如何在python中创建这个程序?

Geo*_*mbe 2 python python-3.x

我试着这样做:你输入一个这样的词:快乐而且程序会返回像yppaHappHy这样的东西.

问题是我只得到一个字母:yH等.

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)

Ily*_*rov 6

你必须使用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)


Jea*_*bre 5

用于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)