python - 从给定字符串中删除字母

标签 python string python-2.7

所以我的家庭作业是从给定的字符串中删除给定名称的首字母,使用用户输入来定义变量。当我运行下面的脚本时,它只注册了一个名字。

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/

相关文章:

Python 2.7 - 如何以编程方式从 stdin 读取二进制数据

python - PyCUDA 核函数

python - 学习Python和Scrapy

javascript - 从字符串中删除标点符号?

phpDocumentor 如何记录字符串参数的可用选项

java - 理解字符串和等于

python - 返回未排序多维数组 A 中最接近 B 的函数?

Python逐字节异或解密

python - 如何使用python向eventhub发送多条消息

Python C API : T_INT was not declared in this scope