【问题标题】:How to match words in a list with user input in python?如何将列表中的单词与python中的用户输入匹配?
【发布时间】:2013-07-15 01:10:33
【问题描述】:

我正在开发一个程序,该程序接受用户输入并将列表中的单词替换为“x”。 例如,这个词很烂,用户输入是“这个词很烂”。输出应该是“这个词是 xxxxx.

这是我到目前为止所拥有的。如何访问列表中的元素并与用户输入匹配?

def main():
    message = []
    words = ['drat','crap','sucks']
    counter = 0
    userInput = str(input("Enter The Sentense: "))
    truncatedInput = userInput[:140]
    sentence =  truncatedInput.split()
    for i in range(len(sentence)):

【问题讨论】:

标签: python


【解决方案1】:
def main():
    final_message = []
    words = ['drat','crap','sucks']
    counter = 0
    userInput = input("Enter The Sentense: ")  # use raw_input if you're using python2.X
    truncatedInput = userInput[:140]
    sentence =  truncatedInput.split()
    for word in sentence:
        if word in words:
            word = 'x' * len(word)
        final_message.append(word)
     print ' '.join(final_message)

【讨论】:

  • 感谢您的回答。完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 2021-10-19
  • 2022-12-10
相关资源
最近更新 更多