Reputation: 21
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?
Upvotes: 0
Views: 1317
Reputation: 53688
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.
Upvotes: 4
Reputation: 6274
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.
Upvotes: 1
Reputation: 28292
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.
Upvotes: 1
Reputation: 11039
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.
Upvotes: 1