Using for, .split() and if



我写了什么:

st = 'Print only the words that start with s in this sentence' 
x = st.split()
print(x)
for letter in st:
if letter=='s':
print(letter)

请帮我解决这个问题。我是Python的新手。我试过思考,但我似乎没有破解代码的逻辑部分

x = st.split()
for word in x:
if word.startswith("s"):
print(word)

应该可以

现有代码的问题在于,您将字符串st拆分为一个列表,其中每个单词都作为一个单独的项目(您将其标记为x(,但随后您将继续迭代原始字符串st,而不是刚刚创建的单词列表x

为您提供4种不同的解决方案,它们在实现的内容上是相同的,所有这些方案都在st.split()创建的单词列表上迭代,并且所有这些解决方案都使用字符串方法.startswith()来过滤掉不以"开头的单词;s";。

解决方案1:使用if逻辑过滤for循环

st = 'Print only the words that start with s in this sentence'
for word in st.split():
if word.startswith('s'):
print(word)

解决方案2:使用生成器表达式

st = 'Print only the words that start with s in this sentence'
for word in (w for w in st.split() if w.startswith('s')):
print(word)

解决方案3:将filter函数与lambda函数一起使用:

st = 'Print only the words that start with s in this sentence'
for word in filter(lambda w: w.startswith('s'), st.split()):
print(word)

解决方案4:将filter函数与operator.methodcaller:一起使用

from operator import methodcaller
st = 'Print only the words that start with s in this sentence'
for word in filter(methodcaller('startswith', 's'), st.split()):
print(word)

最新更新