简体   繁体   English

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

[英]Removing Uppercase Letters from a String in Python

I am trying to write a function eliminate that takes a string and 2 optional arguments. 我正在尝试编写一个功能消除,该功能需要一个字符串和2个可选参数。 The first optional argument (bad_characters) takes a letter and the third argument (case_sensitive) takes a Boolean value. 第一个可选参数(bad_characters)采用字母,第三个可选参数(case_sensitive)采用布尔值。 The function should take a string s and remove all instances of bad_characters. 该函数应采用字符串s并删除bad_characters的所有实例。 If case_sensitive is true, then the function should act case sensitive. 如果case_sensitive为true,则该函数应区分大小写。 If false, then it does not need to. 如果为假,则不需要。 This is what I have so far. 到目前为止,这就是我所拥有的。

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

I am having a hard time figuring out how to make the function remove upper case letters if needed. 我很难弄清楚如何使函数在需要时删除大写字母。 The function should also work if bad_characters is a list, tuple, or string. 如果bad_characters是列表,元组或字符串,则该函数也应起作用。

Your problem is miss understanding about str.replace because it just replace one character so you need to loop over bad_characters and remove them one by one. 你的问题是想念理解str.replace ,因为它只是替换一个字符,所以你需要循环bad_characters并删除它们一个接一个。

SO instead of using == you can just use in operand,for check the membership, and then remove character from your string : 因此,而不是使用==你可以使用in操作中,检查会员,然后删除character从字符串:

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

And as a more pythonic way for remove a special characters from string you can use str.translate method : 作为从字符串中删除特殊字符的更Python方式,您可以使用str.translate方法:

s.translate(None,bad_characters)

You can use a very handy str.swapcase function here. 您可以在此处使用非常方便的str.swapcase函数。 Please note that the below code overrides bad_characters for clarity, but you can easily modify it to keep it unchanged. 请注意,以下代码为清楚起见覆盖了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
a = 'AbCdEfG'
print(''.join([x[0] for x in zip(a, a.upper()) if x[0] != x[1]]))
# bdf

You may use the string.translate (python2). 您可以使用string.translate (python2)。

string.translate(s, table[, deletechars]) string.translate(s,table [,deletechars])

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. 从deletechars中的s中删除所有字符(如果存在),然后使用table转换字符,该表必须是256个字符的字符串,为每个字符值提供翻译,并按其序号索引。 If table is None, then only the character deletion step is performed. 如果table为None,则仅执行字符删除步骤。

Other mistakes in the code: 代码中的其他错误:

  • Initialize case_sensitive only with True . 仅使用True初始化case_sensitive True or False is True . True or FalseTrue
  • While True then break adds nothing. While True之后, break不会增加任何东西。 Remove it. 去掉它。
  • if case_sensitive = False: is an assignment while you need a comparison == . if case_sensitive = False:是需要比较==的分配。 case_sensitive is a boolean, so just use it is if case_sensitive or if not case_sensitive . case_sensitive是一个布尔值,因此if case_sensitiveif not case_sensitive ,请使用它。
  • bad_characters == character is wrong. bad_characters == character错误。 You cant compare a list to a character. 您不能将列表与字符进行比较。 use character in bad_characters instead. 请改用character in bad_characters

Here is the whole solution with corrections: 这是带有更正的整个解决方案:

def eliminate(s, bad_characters = [], case_sensitive = True):
    if case_sensitive: #True
        return s.translate(None, "".join(bad_characters))
    else: 
        s = s.translate(None, "".join(bad_characters).lower()) 
        s = s.translate(None, "".join(bad_characters).upper())
        return s
def eliminate(s, bad_characters = [], case_sensitive=True):
    for character in bad_characters:
        if not case_sensitive:
            s = s.replace(character.lower(),'')
            s = s.replace(character.upper(),'')
        else:
            s = s.replace(character,'')
    return s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM