Python 代碼閱讀合集介紹:為什么不推薦Python初學者直接看項目源碼
本篇閱讀的代碼實現將變量名稱轉換為駝峰形式。
本篇閱讀的代碼片段來自於30-seconds-of-python。
camel
from re import sub
def camel(s):
s = sub(r"(_|-)+", " ", s).title().replace(" ", "")
return s[0].lower() + s[1:]
# EXAMPLES
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'
camel
函數接收一個字符串形式的變量名,並將其轉化成駝峰形式。和之前的兩個轉換函數類似,該函數考慮的是變量形式的字符串,單詞與單詞之間有相關分隔,並不是直接連續的單詞,如somefunctionname
。
函數先使用re.sub
函數將字符串中符號形式的分隔符替換成空格形式。然后使用str.title()
將單詞的首字母轉換為大寫。再使用str.replace
函數將所有的空格去除,將所有單詞連接起來。最后函數返回的時候,將字符串的首字母變為小寫。s[1:]
提取字符串從下標1
開始到結尾的切片。