[英]In a list of strings, for each string remove part of a string after a specific character
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'
The problem is in clean_coins = clean_coins.append(test)
.问题出在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.该append
列表的方法修改的列表,并且没有返回,这意味着你要分配的结果clean_coins.append(test)
这是None
以clean_coins
和你得到一个错误的下一个迭代,因为clean_coins
现在None
和你试图在其上调用.append()
。
To fix it just replace clean_coins = clean_coins.append(test)
with clean_coins.append(test)
要修复它,只需将clean_coins = clean_coins.append(test)
替换为clean_coins.append(test)
You can have a 1 liner like the below你可以有一个像下面这样的 1 个衬里
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.