简体   繁体   English

在 python 中将输入的首字母大写并拆分

[英]making first letter of input uppercase with split in python

I got most of the code down but I am having issues getting the string to space back out after making the first letter of each word uppercase我记下了大部分代码,但在将每个单词的第一个字母大写后,我无法将字符串退回空格

here's what I have so far:这是我到目前为止所拥有的:

message = input('Write a short message.') message = input('写一条短信。')

new_message = message.split() new_message = message.split()

glue = ""胶水=“”

for item in new_message:对于 new_message 中的项目:

glue += item[0].upper() + item[1:]胶水 += item[0].upper() + item[1:]

print(glue)打印(胶水)

try with:尝试:

message.capitalize()

If you want to capitalize each word you can try capitalize() and the code will look like this:如果你想将每个单词大写,你可以尝试 capitalize() 代码将如下所示:

  message = input('Write a short message.')
    
  new_message = message.split()
  cap_message = [x.capitalize() for x in new_message]
  print(cap_message)
  • message.split() - split the string into a list using default separator which is any whitespace. message.split() - 使用默认分隔符将字符串拆分为一个列表,该分隔符是任何空格。 The result is a list of words.结果是一个单词列表。
  • capitalize each word in the list using List Comprehention .使用List Comprehention将列表中的每个单词大写。 The list of capitalized words is saved in cap_message variable for code clarity.为了代码清晰,大写单词列表保存在 cap_message 变量中。
  • print the list of capitalized words打印大写单词列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM