繁体   English   中英

如何使用范围将列表中的单词更改为大写/小写-Python

[英]How to change words in a list to upper/lower case using range - 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()

这个怎么样?

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_list”中循环并检查“ 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()

使用适当的IDE进行编码,例如PyCharm。 它会警告您所有的错误。

如果您确实需要使用范围,那将起作用,但是您仍然需要弄清楚打印/返回值。

如果您不知道发生了什么,请在需要的地方放一些print 如果在代码中放入打印件,您将自己解决。

只需对原始代码进行少量修改。 由于要转换为大写/小写,因此还可能要保存输出。 您也可以使用新列表来保存输出,而不是替换原始列表中的值words_list

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)

产量

Enter a poem, verse or saying: My name is bazingaa
['my', 'name', 'is', 'BAZINGAA']

您的代码有几个问题。 word是迭代器的值,因此是整数。 您不能使用的功能upperlower的整数。 但是,您可以通过更简单的方式解决它:

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

在执行上述代码时:

Enter a poem, verse or saying: Programming in Python is great
PROGRAMMING
in
Python
is
great

您还可以使其函数返回列表(也使用range ):

def get(string):
    words_list = string.split()
    output = []
    for i in range(0,len(words_list)):
        word = words_list[i]
        word = word.lower() if len(word) < 4 else word
        if len(word) > 6:word = word.upper()
        output.append(word)
    return output

print(get(input("Enter a poem, verse or saying: ")))

测试:

Enter a poem, verse or saying: Programming in Python is great
['PROGRAMMING', 'in', 'Python', 'is', 'great']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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