电影游戏-跳过电影标题开头的"The"

2024-06-28 11:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

电影游戏是由两个人玩的游戏,具体如下。第一个玩家命名一部电影。然后第二个玩家命名一部新电影,其标题以第一个玩家命名的电影的最后一个字母开头。你知道吗

游戏中我们将忽略定冠词“The”,因此如果一个玩家将电影命名为“她的不在场证明”,那么下一个玩家可以将电影命名为“The Incredibles”,因为冠词“The”被忽略。你知道吗

如何从电影标题中删除“The”?你知道吗

def userInput(lastInput):
    if lastInput == None:
            return str(input("Enter a movie title: ")).lower()
    if lastInput[:4] == "The ": # doesn't work
        lastInput = lastInput[4:] # doesn't work
    while True:
        userChoice = str(input("Enter a movie title: ")).lower()
        if userChoice[0] == lastInput[-1]:
            return userChoice
        else:
            print("\nInvalid input, what would you like to do?")
            instructions()

Tags: the游戏标题inputreturnif电影title
3条回答

你可以这样做:

if lastInput.lower().startswith("the "): lastInput = lastInput[4:]

使用字符串的startswith()方法,可以直接测试第一个单词(包括它后面的空格)。为了支持各种大小写,将字符串转换为小写(使用lower())只允许对任何大小写变体组合(例如“the”、“the”、“the”)执行一个测试。你知道吗

我还注意到,您没有将此排除逻辑应用于userChoice变量,我本希望在这里使用它,而不是应用于lastInput变量。你知道吗

您可以用空字符串替换您提到的中的字符串部分, 使用 下面的代码将从字符串中删除所需的单词

str="The Incredibles"
str.replace("The","")

考虑使用正则表达式

import re
a = r'^(\bthe\b)'
sts  = ['the incredibles', 'theodore', 'at the mueseum', 'their words' ]
for i in sts:
    b = re.sub(a,'', i)
    print(b)

我使用的正则表达式似乎可以工作,但是您可能需要使用以下链接测试更多示例https://regex101.com/r/pX5sD5/3

相关问题 更多 >