所以我的家庭作业是从给定的字符串中删除给定名称的首字母,使用用户输入来定义变量.当我运行下面的脚本时,它只注册一个名称.
def removeChar(initials, string): initials = initials string = string for char in initials: modified = string.replace(char, "") print modified return modified def getInitials(name, string): initials = "" for i in name.lower().split(): initials += i[0] print initials removeChar(initials, string) def main(): name = raw_input("What is your name? \n") string = raw_input("What string would you like to remove your initials from? \n") getInitials(name, string)
这是输出:
What is your name? John Doe What string would you like to remove your initials from? Arjajbian Ndigdhts Arjajbian Nights
为什么不删除第一个首字母?
你的问题在于:
modified = string.replace(char, "")
您始终replace
在原始字符串上使用,因此它会从原始字符串中删除每个单独的字符并返回一个新字符.只是用string = string.replace(char, "")
否则,您的函数将始终返回一个字符串,该字符串是删除了最后一个首字母的原始字符串.