gpt4 book ai didi

python - 访问拆分列表中的某些单词

转载 作者:行者123 更新时间:2023-12-01 05:54:59 24 4
gpt4 key购买 nike

我正在尝试用Python创建一个程序,它接受用户的一个句子,并打乱该单词的中间字母,但保持其他字母完好无损......现在我有代码可以重新排列所有用户输入和只是忘记了空格...我会让我的代码为自己说话..对于单个单词输入来说它工作得很好,我想我只会总结它...我需要随机化用户输入的每个单词,然后保持其他单词完整。

import random


words = input("Enter a word or sentence") #Gets user input

words.split()

for i in list(words.split()): #Runs the code for how many words there are

first_letter = words[0] #Takes the first letter out and defines it

last_letter = words[-1] #Takes the last letter out and defines it

letters = list(words[1:-1]) #Takes the rest and puts them into a list

random.shuffle(letters) #shuffles the list above

middle_letters = "".join(letters) #Joins the shuffled list

final_word_uncombined = (first_letter, middle_letters, last_letter) #Puts final word all back in place as a list

final_word = "".join(final_word_uncombined) #Puts the list back together again

print(final_word) #Prints out the final word all back together again

最佳答案

你的代码几乎是正确的。更正后的版本如下:

import random

words = raw_input("Enter a word or sentence: ")
jumbled = []

for word in words.split(): #Runs the code for how many words there are
if len(word) > 2: # Only need to change long words
first_letter = word[0] #Takes the first letter out and defines it
last_letter = word[-1] #Takes the last letter out and defines it
letters = list(word[1:-1]) #Takes the rest and puts them into a list
random.shuffle(letters) #shuffles the list above
middle_letters = "".join(letters) #Joins the shuffled list
word = ''.join([first_letter, middle_letters, last_letter])

jumbled.append(word)

jumbled_string = ' '.join(jumbled)
print jumbled_string

关于python - 访问拆分列表中的某些单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13052686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com