在 Python 中大写字符串的首字母

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/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") subgraph Lab Skills python/booleans -.-> lab-13596{{"在 Python 中大写字符串的首字母"}} python/comments -.-> lab-13596{{"在 Python 中大写字符串的首字母"}} python/conditional_statements -.-> lab-13596{{"在 Python 中大写字符串的首字母"}} python/lists -.-> lab-13596{{"在 Python 中大写字符串的首字母"}} python/tuples -.-> lab-13596{{"在 Python 中大写字符串的首字母"}} python/function_definition -.-> lab-13596{{"在 Python 中大写字符串的首字母"}} python/default_arguments -.-> lab-13596{{"在 Python 中大写字符串的首字母"}} end

字符串首字母大写

编写一个名为 capitalize_string(s, lower_rest=False) 的 Python 函数,该函数接受一个字符串作为参数,并返回一个首字母大写的新字符串。该函数应具有一个可选参数 lower_rest,如果设置为 True,则将字符串的其余部分转换为小写。

def capitalize(s, lower_rest = False):
  return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])
capitalize('fooBar') ## 'FooBar'
capitalize('fooBar', True) ## 'Foobar'

总结

在这个挑战中,你已经学会了如何在 Python 中把字符串的首字母大写。你可以使用 capitalize() 方法或者编写一个自定义函数来达到同样的效果。