在运行代码以打印以“s”开头的单词时,jupyter note book 没有响应
st = 'Print only the words that start with s in this s'
lis=st.split()
i=0
res=[]
while i<len(lis):
if lis[i][0]=='s':
res.append(list[i])
i+=1
print(res)
最佳答案
如果列表中的第一个单词不是以 s 开头,则您的代码将卡住,将 i 增量更改为超出 if,如下所示:
st = 'Print only the words that start with s in this s'
lis=st.split()
i=0
res=[]
while i<len(lis):
if lis[i][0]=='s':
res.append(list[i])
i+=1
print(res)
编辑:此代码的改进版本
st = 'Print only the words that start with s in this s'
res=[]
for s in st.split():
if s[0] == 's':
res.append(s)
print(res)
你也可以使用列表理解
st = 'Print only the words that start with s in this s'
res = [s for s in st.split() if s[0] == 's']
print(res)
# prints ['start', 's', 's']
关于python - 打印出以 's' 开头的单词时,我的 jupyter 笔记本没有响应是代码错误还是笔记本问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441815/