为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Python 模型中循环遍历字符串?

如何在 Python 模型中循环遍历字符串?

慕码人8056858 2024-01-11 17:38:43
我想在模板中显示女子联赛,这是我的views.py代码:leagues = League.objects.all()for league in leagues:    print(league.name)它将向我显示所有联赛的名称:International Conference of Amateur Ice HockeyInternational Collegiate Baseball ConferenceAtlantic Federation of Amateur Baseball PlayersAtlantic Federation of Basketball AthleticsAtlantic Soccer ConferenceInternational Association of Womens' Basketball PlayersAmerican Conference of Amateur FootballAtlantic Amateur Field Hockey LeagueTransamerican Womens' Football Athletics ConferencePacific Ice Hockey Conference我如何循环遍历这些名称并挑选出包含女子联赛的联赛?
查看完整描述

2 回答

?
达令说

TA贡献1821条经验 获得超6个赞

简单,使用containsicontains因为不区分大小写的搜索:

leagues = League.objects.filter(name__icontains='women')

for league in leagues:

    print(league.name)


查看完整回答
反对 回复 2024-01-11
?
冉冉说

TA贡献1877条经验 获得超1个赞

您可以league.name在打印之前检查小写字母是否包含“women”:


leagues = League.objects.all()

for league in leagues:

    if "women" in league.name.lower():

        print (league.name)


查看完整回答
反对 回复 2024-01-11
  • 2 回答
  • 0 关注
  • 105 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信