Making letters uppercase using re.sub in python?

后端 未结 5 969
死守一世寂寞
死守一世寂寞 2020-11-30 07:26

In many programming languages, the following

find foo([a-z]+)bar and replace with GOO\\U\\1GAR

will result in the entire match bei

5条回答
  •  一整个雨季
    2020-11-30 08:02

    For those coming across this on google...

    You can also use re.sub to match repeating patterns. For example, you can convert a string with spaces to camelCase:

    def to_camelcase(string):
      string = string[0].lower() + string[1:]  # lowercase first
      return re.sub(
        r'[\s]+(?P[a-z])',              # match spaces followed by \w
        lambda m: m.group('first').upper(),    # get following \w and upper()
        string) 
    
    to_camelcase('String to convert')          # --> stringToConvert
    

提交回复
热议问题