如果我将列表中的字符串与字符串变量进行比较,它是检查单词中的所有字符还是检查列表中的单词本身
If i am comparing a string in a list to a string variable, is it checking all the characters in the word or the word itself on the list
我是使用 Python 的新手程序员。下面的示例是一个名为 censor 的函数,它接受两个字符串(文本和单词)作为输入。它应该 return 用星号替换您选择的单词的文本。
例如,如果 text="hello and shoutout to everyone" 和 word="everyone",输出应该是:
“你好并向 ******** 致意”
def censor(text, word):
text = text.lower()
text_to_list = text.split()
for i in text_to_list:
if i == word:
text = text.replace(i, '*' * len(word))
print(text)
我上面的函数看起来像是在完成工作,但是当我设置时:
text="joey is a buggie bug" 和 word="bug",文本字符串中的 buggie 也带有星号。有人可以告诉我我错过了什么或者比较类型有误吗?我试图检查 'i' 和 'word' 的类型,它们都给我“class 字符串”。任何帮助都会很棒。
你错过了一个比较,你的“单词”前后除了空格外没有其他符号
如果只找到一个,您将替换 word
的所有实例,您必须每次手动替换它:
def censor(text, word):
text = text.lower()
text_to_list = text.split()
out = []
for i in text_to_list:
out.append('*' * len(word) if i == word else i)
print(' '.join(out))
我是使用 Python 的新手程序员。下面的示例是一个名为 censor 的函数,它接受两个字符串(文本和单词)作为输入。它应该 return 用星号替换您选择的单词的文本。
例如,如果 text="hello and shoutout to everyone" 和 word="everyone",输出应该是:
“你好并向 ******** 致意”
def censor(text, word):
text = text.lower()
text_to_list = text.split()
for i in text_to_list:
if i == word:
text = text.replace(i, '*' * len(word))
print(text)
我上面的函数看起来像是在完成工作,但是当我设置时: text="joey is a buggie bug" 和 word="bug",文本字符串中的 buggie 也带有星号。有人可以告诉我我错过了什么或者比较类型有误吗?我试图检查 'i' 和 'word' 的类型,它们都给我“class 字符串”。任何帮助都会很棒。
你错过了一个比较,你的“单词”前后除了空格外没有其他符号
如果只找到一个,您将替换 word
的所有实例,您必须每次手动替换它:
def censor(text, word):
text = text.lower()
text_to_list = text.split()
out = []
for i in text_to_list:
out.append('*' * len(word) if i == word else i)
print(' '.join(out))