0

I want to remove the letters from row[1] and row[2] or if they are empty put None. The loop places None works fine but when it get to the other loop if it encounters a None I get the error. How can I fix it? Thanks in advance!

a = [['something', 'G3535354', '33453421D'], ['something', '', 'R3848347']]

i = 0
char_no = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for row in a:
  j = 0
  for col in row:
    if a[i][j] == '':
      a[i][j] = None
    j += 1
  for character in char_no:
    row[1] = row[1].replace(character, "")
    row[2] = row[2].replace(character, "")
  i += 1

print(a)
4
  • 2
    Tip: read up about enumerate. That avoids using extra lines such as i = 0, i += 1 etc. Commented Nov 28, 2021 at 21:25
  • 1
    Also: the Python standard uses 4 spaces for indentation, not 2. Commented Nov 28, 2021 at 21:25
  • 2
    If you set an element of your nested list to None, it's not a string anymore. In the next loop, however, you use a string method on that element, namely, .replace(). So you'd get None.replace(character, ""). That will obviously fail. Commented Nov 28, 2021 at 21:27
  • 2
    Perhaps you should just switch the two inner loops around; see if that works. Because replacing characters in an empty string does nothing, thus, an empty string remains empty, and you can later replace it by None. Commented Nov 28, 2021 at 21:28

1 Answer 1

1

Let's look at the error you get when you run your code:

AttributeError: 'NoneType' object has no attribute 'replace'

As you already know, this happens in second loop, when you already placed None in your lists. You are trying to do None.replace(character,"") and it is not possible as None is not a string.

This will work:

if row[1]:
    row[1] = row[1].replace(character, "")
if row[2]:
    row[2] = row[2].replace(character, "")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.