将单词首字母大写

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,我们可以使用内置函数将字符串中每个单词的首字母大写。在这个挑战中,你将被要求编写一个函数,该函数接受一个字符串作为参数,并返回一个新的字符串,其中每个单词的首字母都大写。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/comments -.-> lab-13595{{"将单词首字母大写"}} python/function_definition -.-> lab-13595{{"将单词首字母大写"}} end

将每个单词的首字母大写

编写一个函数 capitalize_every_word(s),它接受一个字符串 s 作为参数,并返回一个新的字符串,其中每个单词的首字母都大写。

def capitalize_every_word(s):
  return s.title()
capitalize_every_word('hello world!') ## 'Hello World!'

总结

在这个挑战中,你已经学会了如何使用 Python 中的内置函数将字符串中每个单词的首字母大写。这项技能在各种应用中都可能有用,比如格式化文本以进行显示或处理用户输入。