[英]How do I get my (if “input” in list) to check every letter of the input and not just the first letter of input?
How do I get my (if "input" in list) to check every letter of the input and not just the first letter of input? 如何获得我(如果在列表中为“输入”)检查输入的每个字母,而不仅仅是输入的第一个字母?
This is my code now: 现在是我的代码:
alphabet = "abcdefghijklmnopqrstuvwxyzæø˚a ?"
my_list=list(alphabet)
n= input()
def textis():
for word in n.split():
if word in my_list:
print(word)
else:
x=word.replace(n,"?")
print (x)
textis()
but it only checks the first letter of the input. 但它仅检查输入的首字母。 I want it to check every letter of input and change the ones that dont are in list to "?", and print the input again with the changes "?" 我希望它检查输入的每个字母,并将列表中不存在的字母更改为“?”,然后使用更改“?”再次打印输入。 in the sentence. 在句子中。 So if input is, hello My name Is, output should be hello ?y name ?s. 因此,如果输入为hello我的名字是,输出应为hello?y name?s。
Here are the problems: 这里是问题:
What I did was make a new variable and made changes to that variable and then returned this variable. 我所做的是制作一个新变量,然后对该变量进行了更改,然后返回了该变量。
alphabet = "abcdefghijklmnopqrstuvwxyzæø˚a ?"
my_list = list(alphabet)
n = input()
def textis(n, my_list):
new = ''
for letter in n:
if letter in my_list:
new += letter
else:
new += "?"
return new
print(textis(n, my_list))
Your function will work as is with a slight modification. 稍作修改,您的功能将照常工作。 when you n.split()
you are generating a list of words, n.split() == ['hello', 'My', 'name', 'Is']
so when you iterate for word in n.split(): if word in my_list
you are comparing words like name
vs individual letters in my_list
, you will never get a match. 当您使用n.split()
,会生成一个单词列表, n.split() == ['hello', 'My', 'name', 'Is']
因此当您for word in n.split(): if word in my_list
你比较喜欢的话name
VS个别字母my_list
,你将永远不会得到匹配。 instead you have to use another level of nesting, for i in word
, then it will work! 取而代之的是,您必须使用另一层嵌套, for i in word
,那么它将起作用! (Also there is no need to create a list out of alphabet
for this case, you can use it as is) (在这种情况下,也无需alphabet
创建列表,您可以按原样使用它)
alphabet = "abcdefghijklmnopqrstuvwxyzæø˚a ?"
n= input()
def textis():
for word in n.split():
for i in word:
if i in alphabet:
pass
else:
word = word.replace(i,"?")
print(word)
textis()
All this being your program is still returning all words on separate lines and a little over doing for the task, instead something like this would do the trick. 所有这些都成为您的程序,仍然会在单独的行上返回所有单词,并且为该任务做的工作有点过头了,相反,这种方法可以解决问题。
s = input('Enter a word: ')
for i in s:
if i not in alphabet:
s = s.replace(i, '?')
# hello ?y name ?is
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.