使用.split()仅输出‘s’,如何实现筛选输出以‘s’开头的单词?
解决方法
首先,split()方法的作用是把字符串按指定分隔符(默认是空格)拆分成单词列表,而不是逐个字符。你之前的问题应该是直接遍历了原字符串,导致拿到的是单个字符而非单词。
以下是符合要求的代码:
st = 'Print only the words that start with s in this sentence' # 用split()把字符串拆成单词列表 words = st.split() # 遍历每个单词 for word in words: # 判断单词是否以's'开头 if word.startswith('s'): print(word)
代码说明:
st.split():将原字符串按空格分割,得到类似['Print', 'only', 'the', 'words', 'that', 'start', 'with', 's', 'in', 'this', 'sentence']的单词列表。for word in words:逐个取出列表里的每个单词。word.startswith('s'):检查当前单词是否以小写字母s开头,符合条件就打印该单词。
运行这段代码会输出:
start s sentence
内容的提问来源于stack exchange,提问作者xdkyaka
相关产品推荐
相关产品推荐

