0

I have a list of strings and I would like to get rid of the part of the string after the character '_', but it gives me an error I can't find

import requests
url = 'https://data.gateapi.io/api2/1/pairs'
r = requests.get(url = url)
coins = r.json()
print(coins)
['USDT_CNYX', 'BTC_USDT', 'BCH_USDT', 'ETH_USDT', 'ETC_USDT', 'QTUM_USDT', 'LTC_USDT', 'DASH_USDT', 'ZEC_USDT', 'BTM_USDT', 'EOS_USDT', 'REQ_USDT', 'SNT_USDT', 'OMG_USDT']

clean_coins = []
for coin in coins:
    test=coin.split("_")
    test = test[0]
    clean_coins = clean_coins.append(test)

AttributeError: 'NoneType' object has no attribute 'append'
  • `clean_coins.append(test)` not `clean_coins = clean_coins.append(test)` – SamBob Oct 16 '21 at 08:18
  • `clean_coins = clean_coins.append(test)` -- > `clean_coins.append(test)` – balderman Oct 16 '21 at 08:19
  • "but it gives me an error I can't find" Really? I can literally copy and paste `AttributeError: 'NoneType' object has no attribute 'append'` [into a search engine](https://duckduckgo.com/?q=AttributeError%3A+%27NoneType%27+object+has+no+attribute+%27append%27) and get one of the duplicates I linked as the first result. – Karl Knechtel Oct 27 '21 at 12:55

2 Answers2

2

The problem is in clean_coins = clean_coins.append(test).

The append method of a list modifies the list and returns nothing, this means that you are assigning the result of clean_coins.append(test) which is None to clean_coins and on the next iteration you get an error because clean_coins is now None and you are trying to call .append() on it.

To fix it just replace clean_coins = clean_coins.append(test) with clean_coins.append(test)

Matteo Zanoni
  • 3,429
  • 9
  • 27
1

You can have a 1 liner like the below

coins = ['USDT_CNYX', 'BTC_USDT', 'BCH_USDT', 'ETH_USDT', 'ETC_USDT', 'QTUM_USDT', 'LTC_USDT', 'DASH_USDT', 'ZEC_USDT', 'BTM_USDT', 'EOS_USDT', 'REQ_USDT', 'SNT_USDT', 'OMG_USDT']

clean_coins = [x.split('_')[0] for x in coins]
print(clean_coins)

output

['USDT', 'BTC', 'BCH', 'ETH', 'ETC', 'QTUM', 'LTC', 'DASH', 'ZEC', 'BTM', 'EOS', 'REQ', 'SNT', 'OMG']
balderman
  • 22,927
  • 7
  • 34
  • 52