为了账号安全,请及时绑定邮箱和手机立即绑定

替换python中的字符串字符

替换python中的字符串字符

翻翻过去那场雪 2021-07-04 16:40:59
我正在制作一个用户输入一些文本的程序,并且我不想将该文本中不在变量“alfabet”中的所有字符更改为“?”。我怎样才能做到这一点?我还想在两个函数中完成它,main 和 clean_text。我的代码现在看起来像这样:def clean_text():for char in text:if char in alfabeth:continueelif 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)
查看完整描述

2 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

您必须返回一些东西才能将其分配给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 text


if __name__ == '__main__':

    text = main()

    print(clean_text(text))

Type in text: vash the stampede

v?sh th? st?mp?d?


查看完整回答
反对 回复 2021-07-06
  • 2 回答
  • 0 关注
  • 132 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号