如何在不使用函数但使用方法或循环的情况下从python中的特定字母开始打印单词。
1)我有一个字符串,想要打印以'm'开头的单词
St= "where is my mobile"
result =“我”,“移动”
2)对于以下列表,如何输出以“ p”开头的列表,该列表可以是上下两个。
List = ['mobile',"pencil","Pen","eraser","Book"]
谢谢
Nb:这不是作业,只是python新手
答案 0 :(得分:1)
使用str.startswith
例如:
St= "where is my mobile"
for i in St.split():
if i.startswith("m"):
print(i)
输出:
my
mobile
使用filter
例如:
L = ['mobile',"pencil","Pen","eraser","Book"]
print( list(filter(lambda x: x.lower().startswith("p"), L)) )
输出:
['pencil', 'Pen']
答案 1 :(得分:1)
尝试以下代码:
#String to be splitted
St = 'where is my mobile'
#Split the string on blank characters
List = St.split()
#for each element in the list, if it starts with 'm' then print it
for s in List:
if s.startswith('m'):
print(s)