'Print value until string index is 0
I am passing dot separated key as a argument. I have used split(".") and then print the value data. Here is my code:
desc = str(sys.argv[1])
st = desc.split(".")
i = 0
print (len(st))
for i in range(len(st)):
for ch in st:
st[i] = ch
print (st[i])
i += 1
print(i)
#print(data[st1][st2]..[stn])
I am getting the output as
3
db
1
dap
2
nodes
3
db
2
db
3
Traceback (most recent call last):
File "getvar.py", line 17, in <module>
st[i] = ch
IndexError: list assignment index out of range
I want the data[db][dap][nodes] which will give me the correct value. How should I proceed?
Solution 1:[1]
You are confusing 2 loops : for item in items and for i in range.
When you use i in range the max value in length -1 because indexes are zero based.
when you have used split st is an array of values so the line st[i] = ch is reloading the value back where is was read from.
Here I give both syntaxes of the loop. You will observe that print(st) before the loops gives the result that you want.
desc="10.12.45.35.66.28"
#desc = str(sys.argv[1])
st = desc.split(".")
print([st])
print ("length:",len(st))
for j in range(len(st)-1):
print (j," -> ", st[j])
i = 0
for ch in st:
st[i] = ch
print (i," -> ", st[i])
i += 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
