如何将 user-inputted 字符串的第一个字母大写但保留字符串的其余部分大写

How to capitalize the first letter of a user-inputted string but keep the rest of the string's capitalization

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

def main():

 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)

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

# 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 位替换“句子”

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

很简单:你可以在字符串的一部分上使用 String 方法 upper()。

这是一个单行代码:

CapWord = "".join([c.upper() if i == 0 else c for i, c in enumerate([j for j in rawWord])])

只需将 CapWord 和 rawWord 替换为各自的值即可(您可以根据需要将它们更改为句子/单词。

它的作用:

  • 用字符串中的所有字符及其各自的枚举遍历数组(以避免重复的字母也被大写)然后检查 char (c) 是否有对应于要大写的索引的数字,并且是转换为字符串。