1
h = list('camelCase')

for i in range(len(h)):
    if h[i].isupper():
        h.insert(i,' ')

print(h) returns: ['c', 'a', 'm', 'e', 'l', ' ', ' ', ' ', ' ', 'C', 'a', 's', 'e']

I expected: ['c', 'a', 'm', 'e', 'l', ' ', 'C', 'a', 's', 'e']

since there's only one uppercase letter "C"

1
  • 2
    Try putting print(h, i, h[i]) before if h[i].isupper(): and see what is happening. Usually it is not good to modify a list during a for loop over the list. Commented May 15, 2022 at 5:54

3 Answers 3

1

Changing the list you are iterating on isn't always a good idea but if you want to apply it on the same list you can use while loop:

h = list('camelCase')

i = 0
while (i < len(h)):
    if h[i].isupper():
        h.insert(i,' ')
        i += 1
    i += 1
Sign up to request clarification or add additional context in comments.

Comments

1

You need to copy the original list first.

The reason the space letters are added repeatedly is that " " is added in the list h so "C" is taken continuously until the index i reaches the original length of h.

h = list('camelCase')
a = h.copy()

for i in range(len(h)):
    if h[i].isupper():
        a.insert(i,' ')
print(a)

Comments

0

Your issue is that you are iterating over the range of the list, and when you find a capital letter, you insert the space in that position, which means that the capital letter will be move to the next position, therefore once you find a capital letter it will simply add a space and check that letter again.

Your h[i] right now would print the following:

`c`, `a`, `m`, `e`, `l`, `C`, `C`, `C`, `C` 

My recommendation would be to not modify the original list, but do it in a separate one:

h = list('camelCase')
new_text = ''

for i in range(len(h)):
    if h[i].isupper():
        new_text += ' '
    new_text += h[i]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.