python выдаёт IndexError: string index out of range
Программа должна преобразовать "The_Cat-Was-pippi" в "TheCatWasPippi" и "the_stealth_warrior" в "theStealthWarrior" Но появляется ошибка:
File "/workspace/default/tests.py", line 5, in <module>
test.assert_equals(to_camel_case(''), '', "An empty string was provided but not returned")
File "/workspace/default/solution.py", line 3, in to_camel_case
if text[0].isupper():
IndexError: string index out of range ```
#Код
def to_camel_case(text):
text = text.replace('-', ' ').replace('_', ' ')
if text[0].isupper():
return text.title().replace(' ', '')
elif text=='':
return ""
else:
text = text.title().replace(' ', '')
return text.replace(text[0], text[0].lower(), 1)
print(to_camel_case('The_Cat-Was-pippi'))
print(to_camel_case('the_stealth_warrior'))
Ответы (2 шт):
Автор решения: gil9red
→ Ссылка
У вас есть проверка на пустую строку text=='', но почему-то проверяете после того как было обращение к ее элементам text[0] (кст лучше проверять строки, и не только, через булевые проверки, например через not).
Немного переписал код
Пример:
def to_camel_case(text: str) -> str:
if not text:
return ''
text = text.replace('-', ' ').replace('_', ' ')
if text[0].isupper():
return text.title().replace(' ', '')
text = text.title().replace(' ', '')
return text.replace(text[0], text[0].lower(), 1)
UPD. без дублирования кода:
def to_camel_case(text: str) -> str:
if not text:
return ''
first_char_is_lower = text[0].islower()
text = text.replace('-', ' ').replace('_', ' ')
text = text.title().replace(' ', '')
if first_char_is_lower:
text = text[0].lower() + text[1:]
return text
Автор решения: Сергей Ш
→ Ссылка
def to_camel_case(text):
txt = text.replace('_', '-').split('-')
return ''.join([i.capitalize() for i in txt])
print(to_camel_case('The_Cat-Was-pippi'))
print(to_camel_case('the_stealth_warrior'))
TheCatWasPippi
TheStealthWarrior