修复了我对名称格式大写规则的实现(例如McStuff)



当我输入姓氏(如mcstuff)时,它会打印Welcome Joe Mcstuff!。相反,我希望它说Welcome Joe McStuff!

我不知道为什么第三个字母不大写,我觉得我做错了什么。

这是我的代码:

#Just defining strings needed for later
Mc = "Mc"
O = "O'"
#What is your name?
name = raw_input('What is your first name? ')
name2 = raw_input('What is your last name? ')
#Setting up the grammar for all of these weirdly typed names
#Lowering all the letters of the names
game = name.lower()
game2 = name2.lower()
#Separating out the rest of the name from the first letter
lame = game[1:len(game)]
lame2 = game2[1:len(game2)]
#The names with the first letter being uppercase
Name = game[0].upper() + lame
Name2 = game2[0].upper() + lame2
#For the names with a Mc in it
#If the first 2 letters of the last name have "MC" or "Mc", they will get edited by this conditional
#The last name is now transformed by adding an Mc to an uppercase 3rd letter (assuming the first to letters are some variation of Mc), and adding in the rest of the letters from the fourth letter
if Name2[0:1] == "mc" or Name2[0:1] == "MC" or Name2[0:1] == "Mc":
Last_Name = Mc + Name2[2].upper() + Name2[3:len(Name2)]
#For the names with an O'name in it
#If the first letter has an O, it will get edited by this conditional
#Same as the process with the names with an Mc in it, except if they have an O'(name)
elif Name2[0:1] == "O'" or Name2[0:1] == "o'":
Last_Name = O + Name2[2].upper() + Name2[3:len(Name2)]
#For the regular names, or names not caught by the conditionals
else:
Last_Name = Name2
#For the liars with fake names, or the people unfortunate enought to have this long of a name
if len(Name) + len(Name2) > 45:
print "STOP LYING!"
#Lets finally print this beast
else:
print "Welcome " + Name + " " + Last_Name + "!"

您需要检查Name2[0:2]而不是Name2[0:1]才能获得前两个字符。

(在这里你可以找到Python切片表示法的详细解释。)

您已经成为一个错误的牺牲品。

Python中的Slice表示法在[low, high)范围内创建Slice,因此在下限时关闭,在上限时打开。因此s[0:1]等于s[0],并且计算为单个字符-m

首先,了解如何调试代码。只需打印所有变量,看看它们是否包含您的想法。

其次,变量名称非常违反直觉,您不需要太多。

第三,对45的检查是完全无用的。您不能总是期望您的代码具有所有可能的用例。有人可能会把它用于10000个字符的DNA串,因为你永远不会知道。你甚至在评论中提到,人们可能会有更长的名字。为什么让你的程序在长名称上失败,除了你想让它这样做之外,没有其他原因?支持10亿个字符的名称;为什么不呢?这并不是说你不应该用指责来侮辱用户。

第四,是的,问题是索引中的一个错误。但更深层次的问题是,您不知道如何调试代码。

第五,您的程序在例如空名称上引发异常,因为在使用game[0]之前,您没有检查game是否为空。

第六,永远不要使用名为lame的变量。它进入你的潜意识,并创造或显示出对编程的某种态度。

第七,如果可能的话,遵循一定的变量名称约定。要么使用所有小写字母(推荐),要么如果你绝对不同意python世界的其他部分,那么所有小写字母都以大写字母开头,但不要一直更改。最好避免变量名以2结尾,例如Name2。这是有用例的,但通常这只是意味着程序员太懒了,没有发明一个有意义的名称。

解决方案:

#What is your name?
first_name = raw_input('What is your first name? ').lower()
last_name = raw_input('What is your last name? ').lower()
def upper_kth_letter(s, k):
if len(s) > k: # if s[k] exists, i.e. the string is not too short
return s[:k] + s[k].upper() + s[k+1:]
else:
return s
if last_name[:2] in ['mc', 'o'']:
last_name = upper_kth_letter(last_name, 2)
first_name = upper_kth_letter(first_name, 0)
last_name = upper_kth_letter(last_name, 0)
print 'Welcome, %s %s!' % (first_name, last_name)

最新更新