0

Программа должна преобразовать "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'))

3
  • нормально в PyCharm этот код отрабатывает 31 июл 2022 в 10:35
  • @Сергей, print(to_camel_case('')) это должно уронить код :)
    – gil9red
    31 июл 2022 в 10:39
  • 1
    @gil9red, спасибо, ясно. Я проверяю тот тест, что дает автор. Если тест он тут пишет один, а у себя запускает другой, я не трачу на это время, так как пока это не на "автомате" ловится:-) Автору повезло, что вы посмотрели. 31 июл 2022 в 10:50

2 ответа 2

1

У вас есть проверка на пустую строку 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
0
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
1
  • По условию задачи "the_stealth_warrior" станет "theStealthWarrior", а у вас "TheStealthWarrior" :)
    – gil9red
    31 июл 2022 в 11:35

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.