【问题标题】:Print words starts from a particular letter in python? [closed]打印单词从python中的特定字母开始? [关闭]
【发布时间】:2018-07-28 16:42:11
【问题描述】:

如何在python中不使用函数,而是使用方法或循环来打印从特定字母开始的单词。

1 ) 我有一个字符串,想打印以 'm' 开头的单词

St= "where is my mobile"

结果 = “我的”,“手机”

2 ) 对于下面的列表,如何输出以“p”开头的列表,可以是小写也可以是大写。

List = ['mobile',"pencil","Pen","eraser","Book"]
 
 RESULT= "pencil","pen".

谢谢

注:这不是作业,只是python新手

【问题讨论】:

  • 你尝试了什么?向我们展示代码!
  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • @Poshi ,我试过了,但不能超过两三行,对我不起作用

标签: python string python-3.x


【解决方案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']

【讨论】:

  • 好的。我试图使用startswith和split方法创建一个变量并尝试打印它..但它对我没有用..这很好..谢谢
  • 不客气 :)
【解决方案2】:

试试这个代码:

#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)

【讨论】:

  • 谢谢卢卡。干得好……我发现我哪里出错了。
猜你喜欢
  • 2017-04-13
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 2015-07-30
  • 2018-05-06
相关资源
最近更新 更多