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

我想在模板中显示女子联赛,这是我的views.py代码:


leagues = League.objects.all()

for league in leagues:

    print(league.name)

它将向我显示所有联赛的名称:


International Conference of Amateur Ice Hockey

International Collegiate Baseball Conference

Atlantic Federation of Amateur Baseball Players

Atlantic Federation of Basketball Athletics

Atlantic Soccer Conference

International Association of Womens' Basketball Players

American Conference of Amateur Football

Atlantic Amateur Field Hockey League

Transamerican Womens' Football Athletics Conference

Pacific Ice Hockey Conference

我如何循环遍历这些名称并挑选出包含女子联赛的联赛?


慕码人8056858
浏览 106回答 2
2回答

达令说

简单,使用contains或icontains因为不区分大小写的搜索:leagues = League.objects.filter(name__icontains='women')for league in leagues:    print(league.name)

冉冉说

您可以league.name在打印之前检查小写字母是否包含“women”:leagues = League.objects.all()for league in leagues:    if "women" in league.name.lower():        print (league.name)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5