python3.x - 这段代码如何Pythonic?
黄舟
黄舟 2017-04-18 09:41:07
0
5
360
def remove_ignore_char(word):
    ignore_char = ['A', 'B', 'C',
           ]
    for char in ignore_char:
        if char in word:
            word = word.replace(char, '')
    return word
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

répondre à tous(5)
洪涛
from functools import reduce

def remove_ignore_char(s):
    return reduce(lambda s, c: s.replace(c, ''), [s]+['A', 'B'])

Python 2 supprime la première ligne


ou

import re
def remove_ignore_char(s):
    return re.sub('|'.join(['A', 'B']), '', s)
Ty80

Cette méthode est la plus simple~
python3

>>> 'ABCxAxBxFCABxCabc'.translate(''.maketrans('','','ABC'))
'xxxFxabc'
迷茫
import re

def remove_ignore_char(word):
    return re.sub(r'[ABC]', '', word)
伊谢尔伦
你要的解决方案
import string
table = string.maketrans("abcd", "    ")
word = "abcdefg"
word.translate(table)


将上面的代码封装成一个非常通用的函数
def translator(frm="", to="", delete="", keep=None):
    if len(to) == 1:
        to = to * len(frm)
    trans = string.maketrans(frm, to)
    if keep is not None:
        allchars = string.maketrans("", "")
        delete = allchars.translate(allchars, keep.translate(allchars, delete))
    def translate(s):
        return s.translate(trans, delete)
    return translate
abcd_to_empty = translator(frm="abcd", to="    ")
abcd_to_empty(word)
delete_vowels = translator(delete="aoieu")
delete_vowels(word)
del_digits = translator(delete="1234567890")
del_digits("abcdeeeee12223444dkfljadl")
大家讲道理
my $a = "This is aA TestABC"
$a.subst(/[ABC]/, '', :g)
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal