如何用python编写这个程序?

2024-09-24 10:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着这样做:你输入这样一个词:Happy,然后程序返回这样的东西: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)

Tags: import程序inputdef字母positionrandomchange
3条回答

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

如果要打印反向单词,这将是最快的方法:

print(input("writte one word of your choice? : ")[::-1])

在转换列表中的字符串时使用random.shuffle(就地工作)

然后使用str.join转换回字符串

import random

s =  "Happy"

sl = list(s)
random.shuffle(sl)

print("".join(sl))

输出:

pyapH
Hpayp

相关问题 更多 >