电影游戏是两个人玩的游戏,如下所示。第一个播放器命名一部电影。然后,第二个播放器命名一个新电影,其标题以第一个播放器命名的电影的最后一个字母开头。
游戏我们将忽略明确的冠词" The“,因此如果一个玩家将电影命名为"Her Alibi”,下一个玩家可以将电影命名为“超人特工队”,因为冠词" 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()发布于 2019-05-31 01:37:01
您可以使用空字符串替换您提到的中的字符串部分,使用以下代码从字符串中删除所需的单词
str="The Incredibles"
str.replace("The","")发布于 2019-05-31 01:50:41
考虑使用正则表达式
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测试更多示例
发布于 2019-05-31 05:02:21
你可以这样做:
if lastInput.lower().startswith("the "): lastInput = lastInput[4:]使用字符串的startswith()方法,可以直接测试第一个单词(包括后面的空格)。为了支持不同的大小写,将字符串转换为小写(使用lower())允许您仅对大写/小写变体的任意组合执行一次测试(例如"The ","the ","THE ")。
我还注意到,您没有将这个排除逻辑应用于userChoice变量,而不是lastInput变量。
https://stackoverflow.com/questions/56382953
复制相似问题