简体   繁体   中英

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

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)

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, "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM