Home > Mobile >  Weird output when iterating over a python list and change characters in it
Weird output when iterating over a python list and change characters in it

Time:09-02

I have a List called screenName with its input being:

[['107492.öeso2'], ['106268.test4'], ['106239.test3'], ['106216.test2'], ['106190.test1']]

I now have this code to iterate over every letter and remove it until it reaches a dot

for o in screenName:
    for e in o:
        for l in e:
            if l.isdigit():
                e = e.replace(l, '')
            elif l == '.':
                e = e.replace(l, '')
            elif l.isalpha():
                break
        print(e)

The problem now is that the output is this:

öeso
test4
test
test
test

When I expected something like this:

öeso2
test4
test3
test2
test1

What am I missing?

CodePudding user response:

The first item in your list is ['107492.öeso2']. So whenever it encounters a digit, it replaces it with a blank (''). However, as soon as it encounters the digit '2', it replaces all the instances of '2's with blanks. That is why your resultant output is "öeso" and not "öeso2".

Instead of using the replace method, you can use the string slicing method.

The code would go as follows:

for o in screenName:
    for e in o:
        for l in range(len(e)):
            if e[l] == '.':
                e = e[l 1:]
                break
        print(e)

  

Hope this helped. Have a nice day.

  • Related