在Python中从字符串中删除大写字母

2024-06-09 15:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个函数消除,它接受一个字符串和两个可选参数。第一个可选参数(错误的字符)采用字母,第三个参数(区分大小写)采用布尔值。函数应该接受一个字符串s,并删除所有错误字符的实例。如果区分大小写为true,则函数应表现为区分大小写。如果为false,则不需要。这就是我目前所拥有的。在

def eliminate(s,bad_characters = [],case_sensitive = True or False):
    ''' Takes a string s and returns the string with all bad_characters
    removed. If case_sensitive is True, then the function will only
    remove uppercase letters if there are uppercase letters in
    bad_characters.
    String --> String'''
    while True:
        if case_sensitive = False:
            for character in s:
                if bad_characters == character:
                    newlist = s.replace(bad_characters,'')
                    return newlist
        break

我很难弄清楚如何使函数删除大写字母,如果需要的话。如果坏的字符是列表、元组或字符串,那么该函数也应该起作用。在


Tags: the函数字符串falsetrue参数stringif
3条回答
a = 'AbCdEfG'
print(''.join([x[0] for x in zip(a, a.upper()) if x[0] != x[1]]))
# bdf

您可以在这里使用一个非常方便的str.swapcase函数。请注意,为了清晰起见,下面的代码重写了bad_characters,但是您可以很容易地修改它以保持它不变。在

def eliminate(s, bad_characters, case_sensitive):    
    if not case_sensitive:
        bad_characters += map(str.swapcase, bad_characters)
    return ''.join([c for c in list(s) if c not in bad_characters])

print eliminate('AaBb', ['a'], False)    
print eliminate('AaBb', ['a'], True)    
print eliminate('AaBb', ['A'], True) 

Bb
ABb
aBb

您的问题是缺少对str.replace的理解,因为它只是替换一个字符,所以您需要遍历bad_characters并逐个删除它们。在

因此,不必使用==,只需使用in操作数检查成员身份,然后从字符串中删除{}:

def eliminate(s,bad_characters = '',case_sensitive = False):
    ''' Takes a string s and returns the string with all bad_characters
        removed. If case_sensitive is True, then the function will only
        remove uppercase letters if there are uppercase letters in
        bad_characters.
        String --> String'''
    if case_sensitive == False:
        for character in s:
            if  character in bad_characters:
                s = s.replace(character,'')
        return s

作为从字符串中删除特殊字符的更python方法,可以使用str.translate方法:

^{pr2}$

相关问题 更多 >