首页 > 解决方案 > 在 Python 中将句子的开头大写

问题描述

以下代码用于要求用户输入一串句子并且每个句子的开头由函数大写的作业。例如,如果用户输入:'hello. 这些是例句。有三个。输出应该是:'你好。这些是例句。有三个。

我创建了以下代码:

def main():
    sentences = input('Enter sentences with lowercase letters: ')
    capitalize(sentences)

#This function capitalizes the first letter of each sentence
def capitalize(user_sentences):
    sent_list = user_sentences.split('. ')
    new_sentences = []
    count = 0

    for count in range(len(sent_list)):
        new_sentences = sent_list[count]
        new_sentences = (new_sentences +'. ')
        print(new_sentences.capitalize())

main()

此代码有两个问题,我不确定如何更正。首先,它将每个句子打印为一个新行。其次,它在末尾增加了一个额外的句点。使用上面的示例输入,此代码的输出将是:

你好。
这些是例句。
他们三个。。

有没有办法将输出格式化为一行并删除最后一个句点?

标签: pythonstringfunctionloopssplit

解决方案


以下适用于合理干净的输入:

>>> s = 'hello. these are sample sentences. there are three of them.'
>>> '. '.join(x.capitalize() for x in s.split('. '))
'Hello. These are sample sentences. There are three of them.'

如果句号周围有更多不同的空白,您可能必须使用一些更复杂的逻辑:

>>> '. '.join(x.strip().capitalize() for x in s.split('.'))

这将可能是也可能不是您想要的空白标准化。


推荐阅读