[英]How to make this program in python?
我試着這樣做:你輸入這樣一句話: 快樂而且程序會返回像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)
你必須使用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))
使用random.shuffle
轉換列表中的字符串(就地工作)
然后使用str.join
轉換回字符串
import random
s = "Happy"
sl = list(s)
random.shuffle(sl)
print("".join(sl))
輸出:
pyapH
Hpayp
如果你想打印反向字,這將是最快的方法:
print(input("writte one word of your choice? : ")[::-1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.