Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

Python | 文字列をキャメルケースに変換

概要

文字列をキャメルケースに変換

サンプルコード

StringUtils.py
# -*- coding: utf-8 -*-
import re
class StringUtils:
  @classmethod
  def to_camel(cls, value, capitalize): 
    if (value == None):
      return None
    ret = value.lower()

    words = re.split("[\s_]", ret)
    words = map(lambda x: x.capitalize(), words)
    if (capitalize == False):
      words[0] = words[0].lower()

    return "".join(words)
exec_camel.py
# -*- coding: utf-8 -*-
from string_utils import *

def exec_camel(capitalize):
  print StringUtils.to_camel("hoge", capitalize)
  print StringUtils.to_camel("HOGE", capitalize)
  print StringUtils.to_camel("HOGE_hoge", capitalize)
  print StringUtils.to_camel("", capitalize)
  print StringUtils.to_camel("HOGE hoge", capitalize)
  print StringUtils.to_camel(None, capitalize)

exec_camel(False)
print "----------------------------------------"
exec_camel(True)
出力
hoge
hoge
hogeHoge

hogeHoge
None
----------------------------------------
Hoge
Hoge
HogeHoge

HogeHoge
None