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 scenior as what I'm doing. 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.
So my program is indexing through a sting of binary 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 staying 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 also feel free to comment about those as well.
CodePudding user response:
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