所以我的家庭作业是从给定的字符串中删除给定名称的首字母,使用用户输入来定义变量。当我运行下面的脚本时,它只注册了一个名字。
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, "")
否则您的函数将始终返回一个字符串,该字符串是删除了last 首字母的原始字符串。
关于python - 从给定字符串中删除字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41557443/