我有一项家庭作业,要求我检查列表中的每个单词是否包含特定字母,并告诉用户列表中有多少个单词包含该字母。下面是我的代码:
letterSearch = input("Please enter a letter to search for: ")
w = ['', '', '', '']
w[0] = input("Please enter up to 4 words: ")
w[1] = input(": ")
w[2] = input(": ")
w[3] = input(": ")
first = 0
second = 0
third = 0
fourth = 0
for ch in w[0]:
if ch is letterSearch:
first = 1
for ch in w[1]:
if ch is letterSearch:
second = 1
for ch in w[2]:
if ch is letterSearch:
third = 1
for ch in w[3]:
if ch is letterSearch:
fourth = 1
ans = first + second + third + fourth
print(ans, "of the entered words contain the letter", letterSearch)
我遇到的问题是,在作业中,教授希望用户能够输入单词直到按下回车键,而我将可以输入的最大单词数设置为4。一种方法,使用户能够输入任意数量的单词,而单词仍在列表中分开,直到按下回车键?
答案 0 :(得分:0)
以单个字符串读取整个输入,然后使用split
将其分解为单词列表。
答案 1 :(得分:0)
您可以在字符串上使用split
将其分成几部分。只需要求您的用户用一些字符分隔提供给input
的单词:空格是一种方便的字符。然后,您可以根据输入的字符串创建一个列表,然后继续进行其余的分配工作。
>>> w = input("Please enter words separated by spaces:")
Please enter words separated by spaces:one two three four five six
>>> w
'one two three four five six'
>>> w_list = w.split(" ")
>>> w_list
['one', 'two', 'three', 'four', 'five', 'six']
答案 2 :(得分:0)
要使用任意数量的单词分割字符串(假设它们由空格分隔),请使用内置的
.split()
函数,如下所示:
my_str = "this sentence has some words"
print(my_str.split())
>>> ['this', 'sentence', 'has', 'some', 'words']
除此之外,您的代码还存在一些分解问题。鉴于您不知道单词的数量,因此您无法手动在每个单词中搜索字母。最好遍历拼接词的列表:
letter_search = input("Please enter a letter to search for: ")
words = input("Please enter some words: ")
words = words.split()
in_word_count = 0
# Go through the list of words;
for word in words:
# Check if the letter specified is in the word
if letter_search in word:
# Increment the count
in_word_count += 1
print(in_word_count, "of the entered words contain the letter", letter_search)