如何将每个句子的第一个字母大写?

11
我正在尝试编写一个程序,将每个句子的第一个字母大写。目前为止,这是我的代码,但我无法想出如何在句子之间再次添加句号。例如,如果我输入:

你好。再见

输出结果是

你好 再见

并且句号已经消失了。

string=input('Enter a sentence/sentences please:')
sentence=string.split('.')
for i in sentence:
    print(i.capitalize(),end='')
15个回答

0

看起来很多人不会在运行代码之前检查缩进或代码是否存在错误。关于句子中有其他单词需要保持大写的情况下,第一个单词的大写问题可能已经被其他回答者忽略了。如果您想要实现这一点,请尝试以下代码,它将在重复菜单上运行,直到选择退出:

# Purpose: Demonstrate string manipulation.
#
# ---------------------------------------------------------------
# Variable          Type        Purpose
# ---------------------------------------------------------------
# strSelection      string      Store value of user selection.
# strName           string      Store value of user input.
# words             string      Accumulator for loop.


def main():
    print()
    print("-----------------------------------------------------")
    print("|             String Manipulation                   |")
    print("-----------------------------------------------------")
    print()
    print("1: String Manipulation")
    print("X: Exit application")
    print()
    strSelection = input("Enter your menu selection: ")
    if strSelection == "1":
        strName = input("Enter sentence(s) of your choosing:  ")
        strSentences = ""
        words = list(strName.split(". ")) # Create list based on each sentence.
        for i  in range(len(words)): # Loop through list which is each sentence.
            words[i] = words[i].strip() # Remove any leading or trailing spaces.
            words[i] = words[i].strip(".") # Remove any periods.

            words[i] = words[i][:1].upper() + words[i][1:] # Concatenate string with first letter upper.
            strSentences += words[i] + ". " # Concatenate a final string with all sentences.

        # Print results.
        print("Sentences with first word capitalized, \
and other caps left intact: ", strSentences) 
        print()
        main() # Redisplay menu.

    # Bid user adieu.
    elif strSelection.upper() == "X":
        print("Goodbye")
    else:
        print ("Invalid selection")
        main() # Redisplay menu.

main()

0

这个程序用于将每个新句子的第一个单词大写。

def sentenceCapitalizer():

    string===input('Enter a sentence/sentences please:')
    sentence=string.split('.')
    for i in sentence:
        print (i.strip().capitalize()+". ",end='')
sentenceCapitalizer()

这会在末尾添加一个额外的句号。 - Nightforce2

0
你可以在你的打印函数中使用 end='.'
print(i.capitalize(),end='.')

3
如果您的答案太短无法被接受,可能需要解释您试图提出的错误。 - artdanil

0

也许你可以这样做:

string=input('Enter a sentence/sentences please:')
sentence='.'.join([i.capitalize() for i in string.split('.')])
print(sentence)

这只将第一个单词大写。 - Nightforce2

-1

试试这个:

x = 'hello. how are you doing. nice to see. you'
print '.'.join(map(lambda x: x.title(), x.split('.')))

该代码片段将每个单词的首字母都转换为大写字母。例子:Hello. How Are You Doing. Nice To See You. - Nightforce2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接