社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python代码只打印以A开头的字母[副本]

navodith shankar • 5 年前 • 1621 次点击  

w = ["Algorithm", "Logic", "Filter", "Software", "Network", "Parameters", "Analyze", "Algorithm", "Functionality", "Viruses"]

对于范围内的i(len(w)):

if(w == "A"):
    print(w[i])

'打印(w[i].upper()'

输出应为:

分析

我不明白你怎么会得到一个以a开头的词。这就是我目前所知道的。有什么建议吗?我不允许使用任何其他方法,如startswith等。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55898
 
1621 次点击  
文章 [ 2 ]  |  最新文章 5 年前
marcos
Reply   •   1 楼
marcos    5 年前

只需使用 startswith

w = ["Algorithm", "Logic", "Filter", "Software", "Network", "Parameters", "Analyze", "Algorithm", "Functionality", "Viruses"]

for word in w:
    if word.startswith('A'):
        print(word)

>>> Algorithm
>>> Analyze
>>> Algorithm

编辑:因为你不能使用 开始使用

for word in w:
    if word[0] == 'A':
        print(word)
Ayush Garg
Reply   •   2 楼
Ayush Garg    5 年前

如果要将其存储在列表中,也可以使用列表理解:

result = [word for word in w if word[0] == "A"]

或者,只是简单的循环(如果你只想把单词打印出来):

for word in w:
    if word[0] == "A":
        print(word)