Reputation: 23
I'm aware that this is probably a very simple coding mistake, but I am struggling to find information that reflects the same type of scenario as what I'm facing. I'm sure it's out there, but for the sake of not spending hours hunting it down, I thought I'd just ask it.
My program is indexing through a binary string, and I'm trying to use a for
loop to iterate through the string and remove all the leading 0
's. Basically, I just wrote a for
loop with j
as the indexing var and set it to compare the string at index j
to 1
and if it is 1
then slice the string at that point onward...else in the case that it's a 0
. The error is thrown on the if statement line saying TypeError: string indices must be integers.
I'm confused because I thought when you set a for loop the index variable is automatically an integer -- is it not?
imme = "00000000000001001011001100"
for j in imme:
if imme[j] == "1":
dec_imme = imme[j:]
else:
pass
If there are any other ways to do this more efficiently in Python, feel free to comment about those as well.
Upvotes: 1
Views: 1139
Reputation: 19253
for j in imme:
iterates over every character in imme
. You should use for j in range(len(imme)):
if you want integer indices:
imme = "00000000000001001011001100"
dec_imme = ""
for j in range(len(imme)):
if imme[j] == "1":
dec_imme = imme[j:]
break
print(dec_imme) # Prints 1001011001100
But, you don't need a for
loop to accomplish this task; you can use .lstrip()
instead:
print(imme.lstrip("0")) # Prints 1001011001100
Upvotes: 1