首页 > 解决方案 > 如何将用户输入的字符串的第一个字母大写,但保留字符串的其余部分大写

问题描述

基本上正如标题所说,我希望用户输入的句子大写,但在此过程中不会丢失它们的大写。输入应该是两个用句点分隔的句子。我在这里的代码输出了句子,但没有加入或保留其余的大写。

定义主():

 user_input = input("Enter the sentence you would like to be modified!: ").split(". ")
 capitalized_sentences = [user_input[0].upper() + user_input[1:] for sentence in user_input]
 recombined_sentences = ". ".join(capitalized_sentences)

标签: pythonstringuser-inputcapitalization

解决方案


只需将每个拆分的第一个字符编辑为大写:

# For this example, lets use this string. However, you would still use
# user_input = input("...") in your actual code
user_input = "for bar. egg spam."

# Turn the user_input into sentences.
# Note, this is assuming the user only is using one space.
# This gives us ["foo bar", "egg spam"]
sentences = user_input.split(". ")

# This is called a list comprehension. It's a way of writing
# a for-loop in Python. There's tons of documentation on it
# if you Google it.
#
# In this loop, the loop variable is "sentence". Please be mindful
# that it is a singular form of the word sentences.
#
# sentence[0].upper() will make the first letter in sentence uppercase
# sentence[1:] is the remaining letters, unmodified
#
# For the first iteration, this becomes:
# "f".upper() + "oo bar"
# "F" + "oo bar"
# "Foo bar"
capitalized_sentences = [sentence[0].upper() + sentence[1:] 
                         for sentence 
                         in sentences]

# At this point we have ["Foo bar", "Egg spam"]
# We need to join them together. Just use the same ". " we
# used to split them in the beginning!
#
# This gives us "Foo bar. Egg spam."
recombined_sentences = ". ".join(capitalized_sentences)

user_input用你的位替换“句子”

请注意,如果用户输入了您不期望的格式的句子,则可能会出现“问题”。例如,如果用户输入了两个空格而不是一个空格怎么办?然后上面的代码将尝试将空格字符大写。你需要考虑到这一点。


推荐阅读