Aayan Agarwal
Aayan Agarwal

Reputation: 49

Why is it generating an error of index out of range for 1?

def to_camel_case(text):
    text1 = text.replace("-", "")
    text2 = text1.replace("_", "")
    text4 = text2[1]
    if text2.istitle == True :
        return text2
    elif text2[1].islower():
        text3 = text2[2:]
        return text2 + text3.title()

I wrote the above code for camel-casing. But in line 4 , it is showing the following error. "1" can't be out of range enter image description here

Upvotes: 0

Views: 90

Answers (2)

Akib Rhast
Akib Rhast

Reputation: 671

The reason you are getting the above error is because you are passing in an empty string of length=0, i.e. the index at text2[1] does not exist.

So, before manipulating your string add check to see if it is a string.

Upvotes: 0

anatolyg
anatolyg

Reputation: 28241

  1. First character in a string has index 0, not 1. This is a widely used convention: almost in all programming languages, including python.
  2. Empty string doesn't have even first character. So text[1] and text[0] will throw. Before extracting characters from your string, check it for emptiness: if not text: return text or something like that.

Upvotes: 1

Related Questions