Python 如何大写用户输入字符串的第一个字母,但保留字符串的其余部分';资本化

Python 如何大写用户输入字符串的第一个字母,但保留字符串的其余部分';资本化,python,string,user-input,capitalization,Python,String,User Input,Capitalization,基本上正如标题所说,我希望用户输入的句子大写,但在这个过程中不会丢失大写。输入应该是两个用句点分隔的句子。我这里的代码输出句子,但不连接或保留其余的大写字母 def main(): 只需将每个拆分的第一个字符编辑为大写: # For this example, lets use this string. However, you would still use # user_input = input("...") in your actual code user_input

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

def main():


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

# 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)
将“句子”替换为您的
用户输入


注意,如果用户输入的句子的格式不是您期望的格式,则可能会出现“gotcha”。例如,如果用户输入了两个空格而不是一个,该怎么办?然后,上面的代码将尝试将空白字符大写。您需要对此做出解释。

这很简单:您可以对字符串的一部分使用String方法upper()

这里有一个简单的例子:

CapWord = "".join([c.upper() if i == 0 else c for i, c in enumerate([j for j in rawWord])])
只需将CapWord和rawWord替换为各自的值(您可以根据需要将它们更改为句子/单词)

它的作用是:

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

你的意思是你只想让每个句子的第一个单词大写吗?你应该做什么?向我们展示一些示例输入,以及你得到了什么,以及你期望得到什么。这是否回答了你的问题?当我运行“我拥有的”时,它会将用户输入的所有其他内容都大写。例如,如果有人输入到哪里“我最喜欢的角色是查理·布朗。他是一项伟大的运动。”,它会将句子大写,但会删除查理·布朗的大写。我希望它保留所有其他大写字母,以及将每个句子的第一个单词大写。所以你不真的想要
capitalize()
。你只想用它的
.upper()
替换第一个字符。这足够了吗?我尝试使用这个设置并进行了自己的调整,但它给了我一个类型错误,我不太清楚原因。“大写的_句子=[user_input[0]。upper()+user_input[1:]用于user_input中的句子]TypeError:只能连接str(不是“列表”)到strw什么是
类型(用户输入)
给你的?告诉我你通过编辑问题做了什么我在问题中更改了我的代码。我无法让它在不崩溃的情况下拉类型。问题是你没有正确地修改我的代码。它应该是
句子[0]。upper()
句子[1:]
。您只需将第二行的最后一部分,即句子,替换为
用户输入
。强调单数与复数。句子代表句子列表,而句子代表单个句子字符串。如果您需要更多说明,请告诉我。我对其进行了更改并使其生效!非常感谢,我很高兴我已经在这上面呆了很长时间了。你有没有可能解释一下这段代码中发生了什么,让我下次知道?这仍然是一个糟糕的解决方案,因为你在浪费时间处理每一个字母,而你知道你只会调整第一个字母。绝对正确,如果操作为对于更复杂但有效的解决方案,这是简单的(r)。
CapWord = "".join([c.upper() if i == 0 else c for i, c in enumerate([j for j in rawWord])])