编程中的驼峰命名法

PythonPythonBeginner
立即练习

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

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

简介

驼峰命名法是一种命名约定,即复合词或短语的书写方式是第一个单词为小写,后续单词首字母大写。这种命名约定在编程语言中常用于命名变量、函数和类。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/FileHandlingGroup -.-> python/with_statement("Using with Statement") subgraph Lab Skills python/comments -.-> lab-13594{{"编程中的驼峰命名法"}} python/lists -.-> lab-13594{{"编程中的驼峰命名法"}} python/tuples -.-> lab-13594{{"编程中的驼峰命名法"}} python/function_definition -.-> lab-13594{{"编程中的驼峰命名法"}} python/importing_modules -.-> lab-13594{{"编程中的驼峰命名法"}} python/using_packages -.-> lab-13594{{"编程中的驼峰命名法"}} python/standard_libraries -.-> lab-13594{{"编程中的驼峰命名法"}} python/with_statement -.-> lab-13594{{"编程中的驼峰命名法"}} end

驼峰式字符串

给你一个可能包含空格、连字符或下划线的字符串。你的任务是通过移除空格、连字符或下划线,并将除第一个单词外的每个单词的首字母大写,将该字符串转换为驼峰式。结果字符串的首字母应该是小写。

from re import sub

def camel(s):
  s = sub(r"(_|-)+", " ", s).title().replace(" ", "")
  return ''.join([s[0].lower(), s[1:]])
camel('some_database_field_name') ## 'someDatabaseFieldName'
camel('Some label that needs to be camelized')
## 'someLabelThatNeedsToBeCamelized'
camel('some-javascript-property') ## 'someJavascriptProperty'
camel('some-mixed_string with spaces_underscores-and-hyphens')
## 'someMixedStringWithSpacesUnderscoresAndHyphens'

总结

在这个挑战中,你学习了如何通过移除空格、连字符或下划线,并将除第一个单词外的每个单词的首字母大写,来将字符串转换为驼峰式。你使用了 re.sub() 来用空格替换任何 -_,使用正则表达式 r"(_|-)+"str.title() 来将每个单词的首字母大写并将其余字母转换为小写,以及 str.replace() 来移除单词之间的空格。