替换python中的字符串字符

我正在制作一个用户输入一些文本的程序,并且我不想将该文本中不在变量“alfabet”中的所有字符更改为“?”。我怎样才能做到这一点?我还想在两个函数中完成它,main 和 clean_text。我的代码现在看起来像这样:


def clean_text():

for char in text:

if char in alfabeth:

continue

elif char not in alfabeth:

#don't know what to do here

#text[] = "?"


def main():

userInput = input("type in text: ")

text = list(userInput)


if__name__ == "__main__":

main()

clean_text(text)


翻翻过去那场雪
浏览 134回答 2
2回答

炎炎设计

您必须返回一些东西才能将其分配给user_input要传递到的变量clean_text()。这是您项目的工作版本。这也将处理由空格分隔的多个单词。def clean_text(word):    alphabeth = 'vshthstmpd'    for idx, item in enumerate(word):        if item == ' ':            pass        elif item not in alphabeth:            word[idx] = '?'    return ''.join(word)def main():    user_input = input('Type in text: ')    text = list(user_input)    return textif __name__ == '__main__':    text = main()    print(clean_text(text))Type in text: vash the stampedev?sh th? st?mp?d?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python