to_camel_case.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # 1. Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
  2. #Examples
  3. #"the-stealth-warrior" gets converted to "theStealthWarrior"
  4. #"The_Stealth_Warrior" gets converted to "TheStealthWarrior"
  5. # 'if s else s' - 'защита от пустой строки'
  6. # title - преобразует символы в верхний регистр
  7. # translate - заменяет символы
  8. def to_camel_case(s):
  9. #return s[0] + s.title().translate(None, "-_")[1:] if s else s # Так не работает
  10. return s[0] + s.title().translate({ord('_'):None, ord('-'):None})[1:] if s else s
  11. '''
  12. # replace - замена
  13. # Интересный for по списку и join
  14. def to_camel_case(text):
  15. removed = text.replace('-', ' ').replace('_', ' ').split()
  16. if len(removed) == 0:
  17. return ''
  18. return removed[0]+ ''.join([x.capitalize() for x in removed[1:]])
  19. '''
  20. '''
  21. # Как и в первой функции только без защиты от пустой строки
  22. def to_camel_case(text):
  23. return text[:1] + text.title()[1:].replace('_', '').replace('-', '')
  24. '''
  25. '''
  26. # Разобраться с регулярками
  27. import re
  28. def to_camel_case(text):
  29. return re.sub('[_-](.)', lambda x: x.group(1).upper(), text)
  30. '''
  31. '''
  32. # Микс из первого и второго варианта
  33. def to_camel_case(text):
  34. words = text.replace('_', '-').split('-')
  35. return words[0] + ''.join([x.title() for x in words[1:]])
  36. '''
  37. '''
  38. # Перебор по символу
  39. def to_camel_case(text):
  40. cap = False
  41. newText = ''
  42. for t in text:
  43. if t == '_' or t == '-':
  44. cap = True
  45. continue
  46. else:
  47. if cap == True:
  48. t = t.upper()
  49. newText = newText + t
  50. cap = False
  51. return newText
  52. '''
  53. '''
  54. # Мозгодробительный вариант
  55. def to_camel_case(text):
  56. return "".join([i if n==0 else i.capitalize() for n,i in enumerate(text.replace("-","_").split("_"))])
  57. '''
  58. print(to_camel_case("the-stealth-warrior"))
  59. print(to_camel_case("The_Stealth_Warrior"))