如何使用rangepython将列表中的单词改为大写/小写

2024-05-14 03:03:28 发布

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

我的任务之一是获取用户输入,将其转换成一个列表,然后根据每个单词中的字符数,相应地更改为大写/小写。我被告知我必须使用射程,这是我正在挣扎的部分。这是我最近的一次尝试,但没用。如有任何建议,将不胜感激。在

poem = input("Enter a poem, verse or saying: ")
words_list = poem.split()
list_len = len(words_list)
for word in range(0,list_len):
    if len(words_list[word]) < 4:
        word = word.lower()
    elif len(words_list[word]) > 6:
        word = words.upper()

Tags: 用户列表inputlen字符单词建议list
3条回答

只是对原始代码的一个小修改。由于您希望转换为大写/小写,所以您可能还希望保存输出。或者,您可以使用{cd1>替换列表中的新值

for word in range(0,list_len):
    if len(words_list[word]) < 4:
        words_list[word] = words_list[word].lower()
    elif len(words_list[word]) > 6:
        words_list[word] = words_list[word].upper()

print(words_list)

输出

^{pr2}$

这个怎么样?在

poem = input("Enter a poem, verse or saying: ")
words_list = poem.split()
out = ""
for word in words_list:
    if len(word) < 4:
        word = word.lower()
    elif len(word) > 6:
        word = word.upper()
    out += " " + word
print(out)

删除了未编辑的“list_len”变量,在“words”中循环并检查“word”的长度。用“out”变量集中输出。对于输出可能有更好的技术,我只是做了一个简单的。在

poem = input("Enter a poem, verse or saying: ")
words_list = poem.split()
list_len = len(words_list)

# word is not a word here, it was an integer
# by a convention we use 'i' for the iterator here
for i in range(0,list_len):
    # here we assign an actual 'word' to the word variable
    word = words_list[i]
    if len(word) < 4:
        # therefore you couldn't use .lower() or .upper() on the integer
        word = word.lower()
    elif len(word) > 6:
        word = word.upper()

像PyCharm一样使用适当的IDE进行编码。它会提醒你你犯的所有错误。在

如果您真的需要使用range,那么这就可以了,但是您仍然需要计算出打印/返回值。在

如果你不知道发生了什么,只要把一些print放在你需要的地方。如果你在你的代码里加上指纹,你会自己想出来的。在

相关问题 更多 >