简体   繁体   中英

How to make this program in python?

I'm try to make this: your enter a word like this: Happy and than the program returns somethings like : yppaH or appHy .

The problem is that I get just one letter : y or H , etc..

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)

You have to use sample , not 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))

Use random.shuffle on a conversion of the string in a list (works in-place)

Then convert back to string using str.join

import random

s =  "Happy"

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

print("".join(sl))

outputs:

pyapH
Hpayp

如果你想打印反向字,这将是最快的方法:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM