如何使字符串中的所有内容都小写

2024-04-24 10:22:16 发布

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

我正在尝试编写一个函数,它将打印一首诗,将单词向后读,并使所有字符小写。我环顾四周,发现.lower()应该使字符串中的所有内容都小写;但是我似乎无法使它与我的函数一起工作。我不知道我是把它放错了地方,还是.lower()在我的代码中不起作用。欢迎反馈!

下面是我在任何地方输入.lower()之前的代码:

def readingWordsBackwards( poemFileName ):
    inputFile = open(poemFileName, 'r')
    poemTitle = inputFile.readline().strip()
    poemAuthor = inputFile.readline().strip()

    inputFile.readline()
    print ("\t You have to write the readingWordsBackwards function \n")
    lines = []
    for line in inputFile:
        lines.append(line)
    lines.reverse()

    for i, line in enumerate(lines):
        reversed_line = remove_punctuation(line).strip().split(" ")
        reversed_line.reverse()
        print(len(lines) - i, " ".join(reversed_line))

    inputFile.close()

Tags: 函数代码forreadline地方linelowerstrip
4条回答

根据official documentation

str.lower()

返回字符串的副本,其中所有大小写字符[4]都转换为小写。

所以你可以在几个不同的地方使用它,例如

lines.append(line.lower())

reversed_line = remove_punctuation(line).strip().split(" ").lower()

或者

print(len(lines) - i, " ".join(reversed_line).lower())

(这不会存储结果,但只打印结果,因此很可能不是您想要的结果)。

请注意,根据源代码的语言,您可能需要稍加小心,例如this。 另请参阅How to convert string to lowercase in Python的其他相关答案

根据official documentation

str.lower()

返回字符串的副本,其中所有大小写字符[4]都转换为小写。

所以你可以在不同的地方使用它,例如

lines.append(line.lower())

reversed_line = remove_punctuation(line).strip().split(" ").lower()

或者

print(len(lines) - i, " ".join(reversed_line).lower())

(这不会存储结果,但只打印结果,因此很可能不是您想要的结果)。

请注意,根据源代码的语言,您可能需要稍加小心,例如this。 另请参阅How to convert string to lowercase in Python的其他相关答案

您可以将其插入此处,例如:

lines.append(line.lower())

注意line.lower()line本身没有任何作用(字符串是不可变的!),但返回一个新的字符串对象。要使line包含小写字符串,您需要执行以下操作:

line = line.lower()

我想把第二行改成最后一行行可能行得通

print(len(lines) - i, " ".join(reversed_line).lower())

相关问题 更多 >