Removing unwanted characters from a string in Python

前端 未结 9 1886
暖寄归人
暖寄归人 2021-01-18 09:06

I have some strings that I want to delete some unwanted characters from them. For example: Adam\'sApple ----> AdamsApple.(case insensitive) Can someone help

相关标签:
9条回答
  • 2021-01-18 09:58

    Any characters in the 2nd argument of the translate method are deleted:

    >>> "Adam's Apple!".translate(None,"'!")
    'Adams Apple'
    

    NOTE: translate requires Python 2.6 or later to use None for the first argument, which otherwise must be a translation string of length 256. string.maketrans('','') can be used in place of None for pre-2.6 versions.

    0 讨论(0)
  • 2021-01-18 10:07

    Let's say we have the following list:

    states = [' Alabama ', 'Georgia!', 'Georgia', 'georgia', 'south carolina##', 'West virginia?']
    

    Now we will define a function clean_strings()

    import re
    
    def clean_strings(strings):
        result = []
        for value in strings:
            value = value.strip()
            value = re.sub('[!#?]', '', value)
            value = value.title()
            result.append(value)
        return result
    

    When we call the function clean_strings(states)

    The result will look like:

    ['Alabama',
    'Georgia',
    'Georgia',
    'Georgia',
    'Florida',
    'South Carolina',
    'West Virginia']
    
    0 讨论(0)
  • 2021-01-18 10:08

    Try:

    "Adam'sApple".replace("'", '')
    

    One step further, to replace multiple characters with nothing:

    import re
    print re.sub(r'''['"x]''', '', '''a'"xb''')
    

    Yields:

    ab
    
    0 讨论(0)
提交回复
热议问题