I have this list:
List:
00001:GR00034.asd
00001:GR00020.asd
00001:GR00002.asd
...
I want to convert these lines in something like this:
List:
GR34
GR20
GR2
...
I've tried using loops but I can't make it work:
(indexes is the first list presented before)
for idx in indexes: #to limit between the ":" and the "."
i = ((idx).index(":"))
f = ((idx.index(".")))
idx = idx[i 1:f]
list1 = []
for pos in idx: #Iterate trough each character in idx
if pos.isalpha():
list1.append(pos)
else:
if pos != "0":
list1.append(pos)
if idx[-1] == 0: #to add a 0 at the end if necessary
list1 =0
My output is this:
Index List:
1 G
2 R
3 2
4 1
(Just appears the last iteration and separated)
CodePudding user response:
So the problem is stems from the fact your "list1" variable is nested inside the for loop. This means that everytime your loop is iterated, list1 gets reset. To avoid that, you have to define list1 outside of the loop and append to it at the end of each loop. For example:
list1 = []
for idx in indexes: #to limit between the ":" and the "."
i = ((idx).index(":"))
f = ((idx.index(".")))
idx = idx[i 1:f]
entry = ""
for pos in idx: #Iterate trough each character in idx
if pos.isalpha():
entry = entry pos
else:
if pos != "0":
entry = entry pos
if idx[-1] == '0': #to add a 0 at the end if necessary
entry = entry '0'
list1.append(entry)
Here I defined a new variable "entry" that will add all the desired character through the loop, and before the loop resets, I append entry to list1 giving us the characters "G" "R" and non-zeros.
This gives the output: ['GR34', 'GR20', 'GR2']
CodePudding user response:
I don't have enough reputation to comment, so to add to patrick7's post,the final two lines should have 0 as a string, not as an integer
if idx[-1] == "0": #to add a 0 at the end if necessary
list1 ="0"
