You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本if语句判断失效:排除None值仍输出None

问题解决:Shopify产品列表MSRP判断无效的问题
  • 问题根源:你写的if msrp != 'None'是在和字符串'None'做比较,但Shopify API返回的空定价其实是Python的None对象,不是字符串类型。这就导致你的判断完全不生效,None对象自然会被打印出来。

  • 修正后的代码:把判断条件改成检查msrp是否为None对象,同时可以兼容空字符串的情况(部分场景下API可能返回空字符串):

for item in data['products']:
    used = False
    name = item['title']
    url = 'https://' + brand[0] + brand[1] + '/products/' + str(item['handle'])
    handel = item['handle']
    for variant in item['variants']:
        msrp = variant['compare_at_price']
        salePrice = variant['price']
        # 排除None和空字符串的情况
        if msrp is not None and msrp != '':
            print(msrp)
  • 额外说明:如果确定API只会返回None而不会有空字符串,直接用if msrp is not None:就行,加空字符串判断是为了覆盖更多可能的异常情况。

内容的提问来源于stack exchange,提问作者Thebrady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 20:52:03