看到一道題目,只用re.sub(),不得其解。
把下划線命名(也叫蛇形命名,所有單詞都是小寫,中間通過下划線連接),轉化為小駝峰命名法(第一個單詞小寫,其余所有單詞首字母大寫)。
例如'go_to_next_page'
,轉化后改寫為'goToNextPage'
。
請使用正則表達式替換方法,即re.sub()。
參考文章: https://www.jianshu.com/p/f41dcef2bd1b
re.sub函數
re.sub
函數是Python內置的re模塊的一個字符串替換函數,支持正則替換。函數文檔如下:
help(re.sub) Help on function sub in module re: sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.
-
pattern
:是一個正則表達式,匹配要替換的子串。 -
repl
:可以是一個字符串,支持對pattern中分組的后向引用。
-
string
:要進行替換操作的字符串。 -
count
:要替換掉多少個子串(按從左到右的順序),默認值為0,表示替換能被pattern匹配到的所有子串。 -
flags
:正則內置屬性,默認值為0,表示不使用任何內置屬性。
根據文檔,repl
也可以是一個callable
對象(函數),這個函數的入參為pattern正則匹配到的對象,返回值為一個字符串,表示要替換成的字符串。
import re def convert_name_re(name: str) -> str: """ 下划線形式字符串轉成駝峰形式 :param name: 下划線形式字符串 :return: 駝峰形式字符串 """ name = re.sub(pattern=r'(_\w)',repl=lambda x:x.group(1)[1].upper(),string=name) return name # 這里是測試代碼 print(convert_name_re('go_to_next_page')) # 'goToNextPage' print(convert_name_re('crawl_home_site')) # 'crawlHomeSite' # 反過來是一樣的道理 # p = re.compile(r'([a-z]|\d)([A-Z])') # sub = re.sub(p, r'\1_\2', hunp_str).lower() # 這里第二個參數使用了正則分組的后向引用
注:正則的分組及后向引用詳見:python正則表達式系列(4)——分組和后向引用
注:正則內置屬性的用法詳見:python正則表達式系列(3)——正則內置屬性