【问题标题】:how do I assign different variation to a variable so if input matches one of assigned variable then the answer is correct如何为变量分配不同的变体,因此如果输入与分配的变量之一匹配,则答案是正确的
【发布时间】:2019-06-30 21:18:35
【问题描述】:

创建一个猜字游戏,secret_word 可以是任何变体,但我将如何编写不同变体的 secret_word 被程序识别?

在这种情况下,秘密词是“韩国”,我怎样才能统一任何变体还是必须插入每种不同的变体?

secret_word = {"korea", "kOrea", "KoRea", "KoReA", "KOrea, "KORea", 
"Korea", "KOREA"}
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != secret_word and not (out_of_guesses):
    if guess_count < guess_limit:
        guess = input("Guess a word: ")
        guess_count += 1
    else:
        out_of_guesses = True

if out_of_guesses:
print("Maybe Next time! You are out of guesses")
else:
    print("You win!")

【问题讨论】:

    标签: python string variations


    【解决方案1】:

    简而言之:不区分大小写的检查是一个比乍一看要困难得多的问题。 str.casefold() function [python-doc] 应该为此类比较生成一个字符串。

    您检查输入字符串的.casefold()是否与要猜测的字符串的.casefold()相同,例如:

    secret_word = 'korea'
    guess_count = 0
    guess_limit = 3
    
    while guess_count < guess_limit:
        guess = input('Guess a word')
        if guess.casefold() == secret_word.casefold():
            break
        else:
            guess_count += 1
    
    if guess_count < guess_limit:
        print('You win')
    else:
        print('You lose')

    .casefold() 应该由Unicode standard 生成一个字符串,以便不区分大小写 比较。例如在德语中,eszett ß [wiki] 以大写形式映射为:

    >>> 'ß'.lower()
    'ß'
    >>> 'ß'.upper()
    'SS'
    >>> 'SS'.lower()
    'ss'
    >>> 'ß'.lower() == 'SS'.lower()
    False
    

    .casefold() 将返回ss

    >>> 'ß'.casefold()
    'ss'
    >>> 'ss'.casefold()
    'ss'
    >>> 'ß'.casefold() == 'SS'.casefold()
    True
    

    不区分大小写的比较结果是一个难题,因为某些字符没有大小写等价物等。

    【讨论】:

    • 你忘了guess=""吗?还是不需要?我看到了guess = input('猜一个词')
    • @JMin:不,这不是必需的,因为我们在循环中设置了它。
    【解决方案2】:

    我会以小写(或大写)的形式保存秘密,然后将猜测转换为这种情况:

    secret_word = 'korea'
    
    while guess.lower() != secret_word and not (out_of_guesses):
        # loop's body...
    

    【讨论】:

      【解决方案3】:

      您可以使用guess.lower()guess 的每个变体转换为小写。 所以你只需要给出小写的变体。

      降低(自我,/) 返回转换为小写的字符串的副本。
      -- 帮助(str.lower)

      secret_word = "korea"
      guess = ""
      guess_count = 0
      guess_limit = 3
      out_of_guesses = False
      
      while guess.lower() != secret_word and not (out_of_guesses):
          if guess_count < guess_limit:
              guess = input("Guess a word: ")
              guess_count += 1
          else:
              out_of_guesses = True
      
      if out_of_guesses:
          print("Maybe Next time! You are out of guesses")
      else:
          print("You win!")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-28
        • 1970-01-01
        • 1970-01-01
        • 2010-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-10
        相关资源
        最近更新 更多