0

I'm very new to python and have read what I could find on for loops and the del operator, but I still don't understand why my solution to the problem below isn't working:

PROBLEM

Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".

string_bits('Hello') → 'Hlo'
string_bits('Hi') → 'H'
string_bits('Heeololeo') → 'Hello'

SOLUTION

def string_bits(str):
    for i in range(len(str)):
      if i % 2 != 0:
        del[i]
    return str

This just returns a replica of the original string and doesn't delete anything - why aren't the odd numbers in the range being deleted?

1
  • Note: even if that were possible, del[i] wouldn't be the correct syntax; you're deleting the name i, not a piece of the sequence str. Also, don't name a variable str. Commented Jan 9, 2014 at 16:22

4 Answers 4

4

Strings are immutable, meaning you can't just delete arbitrary characters.

To solve your problem I would use slice notation

x = 'Heeololeo'

y = x[::2]

print(y) # Hello

You can find the details here.

Sign up to request clarification or add additional context in comments.

Comments

1

You shouldn't change something that you are iterating over. You should extract the data you need and save it to a new variable and return that.

Comments

1

First, strings are immutable. Second, you're not supposed to modify an iterable while iterating over it.

Make a copy of it, or use a filter:

new_string = ''.join(c for i, c in enumerate(old_string) if i%2 != 0)

Simplified version:

result = []
for i, c in enumerate(old_string):
    if i%2 != 0:
        result.append(c)
new_string = ''.join(result)

An easier, cooler way is to make a slice of it, with the extended slice notation:

new_string = old_string[::2]

Also, avoid using names like str, you'll shadow the useful built-in function.

Comments

1

strings in Python are immutable, meaning that once they are created, they can't be changed. All functions that seem to "change" strings actually return a new version of the string.

Regardless, a good rule of thumb is to not change things you're iterating over. You could use a list comprehension to create a new string with only the character that you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.