207

Вопрос по replace, list, string, python – Удаление списка символов в строке

Error: User Rate Limit Exceeded

string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...

Error: User Rate Limit Exceeded

list = [',', '!', '.', ';'...]

Error: User Rate Limit ExceededlistError: User Rate Limit Exceededstring?

  • Error: User Rate Limit Exceededsimultaneous answer это именно то, о чем спрашивала @Laura, и это должны быть предпочтительные ответы.

    от
  • Error: User Rate Limit ExceededTypeError: translate() takes exactly one argument (2 given)Error: User Rate Limit Exceeded

    от
  • почему python3: TypeError: translate () принимает ровно один аргумент (2 дано)

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededunicode.translate()Error: User Rate Limit Exceededstr.translate()Error: User Rate Limit Exceeded

    от
  • @SvenMarnach что такое карта (ord, u & quot;,!.; & Quot;))? а ты за юникод?

    от
  • @ thg435: Никто не просил об этом, но в любом случае:s.translate(dict.fromkeys(map(ord, u",!.;")))

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededstackoverflow.com/questions/1919096/…Error: User Rate Limit Exceeded

    от Martijn de Milliano
  • Error: User Rate Limit Exceededphp.net/manual/pl/function.str-replace.php ).

    от JustAC0der
16 ответов
  • 15

    Code:

    ''.join(c for c in myString if not c in badTokens)
    

  • 1

    Error: User Rate Limit Exceeded

    reduce(lambda x,y : x.replace(y,"") ,[',', '!', '.', ';'],";Test , ,  !Stri!ng ..")
    

  • 8

    Error: User Rate Limit Exceeded ''.join(re.split(r'[.;!?,]', s))

    Error: User Rate Limit Exceeded

    ''.join(re.split(r'[.;!?,]', s))
    

  • 2

    Error: User Rate Limit Exceeded

    import re
    str = 'this is string !    >><< (foo---> bar) @-tuna-#   sandwich-%-is-$-* good'
    
    // condense multiple empty spaces into 1
    str = ' '.join(str.split()
    
    // replace empty space with dash
    str = str.replace(" ","-")
    
    // take out any char that matches regex
    str = re.sub('[[email protected]#$%^&*()_+<>]', '', str)
    

    this-is-string--foo----bar--tuna---sandwich--is---good

  • 1

    Error: User Rate Limit Exceeded

    list = [",",",","!",";",":"] #the list goes on.....
    
    theString = "dlkaj;lkdjf'adklfaj;lsd'fa'dfj;alkdjf" #is an example string;
    newString="" #the unwanted character free string
    for i in range(len(TheString)):
        if theString[i] in list:
            newString += "" #concatenate an empty string.
        else:
            newString += theString[i]
    

    theString = "lkdsjf;alkd8a'asdjf;lkaheoialkdjf;ad"
    newString = ""
    for i in range(len(theString)):
         if ord(theString[i]) < 48 or ord(theString[i]) > 122: #ord() => ascii num.
             newString += ""
         else:
            newString += theString[i]
    

  • 3

    Error: User Rate Limit Exceeded

    import unicodedata
    
    def remove_accents(input_str):
        nkfd_form = unicodedata.normalize('NFKD', input_str)
        return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])
    

  • 6

    Error: User Rate Limit Exceeded

    def replace_all(text, dic):
      for i, j in dic.iteritems():
        text = text.replace(i, j)
      return text
    

  • 0

    Error: User Rate Limit Exceeded

    def the_replacer(text):
        test = []    
        for m in range(len(text)):
            test.append(text[m])
            if test[m]==','\
            or test[m]=='!'\
            or test[m]=='.'\
            or test[m]=='\''\
            or test[m]==';':
        #....
                test[n]=''
        return ''.join(test)
    

  • 35

    Error: User Rate Limit Exceeded s.translate(None, '!.;,')

    Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

    s.translate(None, '!.;,')
    

  • 3

    Error: User Rate Limit Exceeded

    >>> subj = 'A.B!C?'
    >>> list = set([',', '!', '.', ';', '?'])
    >>> filter(lambda x: x not in list, subj)
    'ABC'
    

  • 108

    Error: User Rate Limit Exceeded s.translate(None, ",!.;")

    Error: User Rate Limit Exceededstr.translate():

    s.translate(None, ",!.;")
    

    Error: User Rate Limit Exceeded

    >>> s = "asjo,fdjk;djaso,oio!kod.kjods;dkps"
    >>> s.translate(None, ",!.;")
    'asjofdjkdjasooiokodkjodsdkps'
    

  • 9

    Error: User Rate Limit Exceeded

    python3translate

    >>> list = [',', '!', '.', ';']
    >>> s = "This is, my! str,ing."
    >>> s.translate({ord(x): '' for x in list})
    'This is my string'
    

  • 0

    Error: User Rate Limit Exceeded

    more_itertools

    import more_itertools as mit
    
    
    s = "[email protected]#"
    blacklist = "[email protected]#"
    
    "".join(mit.flatten(mit.split_at(s, pred=lambda x: x in set(blacklist))))
    # 'ABCDEF'
    

    blacklist

  • 6

    Error: User Rate Limit Exceeded

    for i in replace_list:
        string = string.replace(i, '')
    

    list.

  • 1

    Error: User Rate Limit Exceeded

    print eval('string%s' % (''.join(['.replace("%s","")'%i for i in replace_list])))
    

    def repn(string,replace_list):
        if replace_list==[]:
            return string
        else:
            return repn(string.replace(replace_list.pop(),""),replace_list)
    
    print repn(string,replace_list)
    

  • 254

    Error: User Rate Limit Exceeded

    str.translate:

    >>> chars_to_remove = ['.', '!', '?']
    >>> subj = 'A.B!C?'
    >>> subj.translate(None, ''.join(chars_to_remove))
    'ABC'
    

    join

    >>> sc = set(chars_to_remove)
    >>> ''.join([c for c in subj if c not in sc])
    'ABC'
    

    ''.join(c for c ...)

    re.sub

    >>> import re
    >>> rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
    >>> re.sub(rx, '', subj)
    'ABC'
    

    (re.escape^]

    translate:

    >>> chars_to_remove = [u'δ', u'Γ', u'ж']
    >>> subj = u'AжBδCΓ'
    >>> dd = {ord(c):None for c in chars_to_remove}
    >>> subj.translate(dd)
    u'ABC'
    

    #coding=utf8
    
    import re
    
    def remove_chars_iter(subj, chars):
        sc = set(chars)
        return ''.join([c for c in subj if c not in sc])
    
    def remove_chars_re(subj, chars):
        return re.sub('[' + re.escape(''.join(chars)) + ']', '', subj)
    
    def remove_chars_re_unicode(subj, chars):
        return re.sub(u'(?u)[' + re.escape(''.join(chars)) + ']', '', subj)
    
    def remove_chars_translate_bytes(subj, chars):
        return subj.translate(None, ''.join(chars))
    
    def remove_chars_translate_unicode(subj, chars):
        d = {ord(c):None for c in chars}
        return subj.translate(d)
    
    import timeit, sys
    
    def profile(f):
        assert f(subj, chars_to_remove) == test
        t = timeit.timeit(lambda: f(subj, chars_to_remove), number=1000)
        print ('{0:.3f} {1}'.format(t, f.__name__))
    
    print (sys.version)
    PYTHON2 = sys.version_info[0] == 2
    
    print ('\n"plain" string:\n')
    
    chars_to_remove = ['.', '!', '?']
    subj = 'A.B!C?' * 1000
    test = 'ABC' * 1000
    
    profile(remove_chars_iter)
    profile(remove_chars_re)
    
    if PYTHON2:
        profile(remove_chars_translate_bytes)
    else:
        profile(remove_chars_translate_unicode)
    
    print ('\nunicode string:\n')
    
    if PYTHON2:
        chars_to_remove = [u'δ', u'Γ', u'ж']
        subj = u'AжBδCΓ'
    else:
        chars_to_remove = ['δ', 'Γ', 'ж']
        subj = 'AжBδCΓ'
    
    subj = subj * 1000
    test = 'ABC' * 1000
    
    profile(remove_chars_iter)
    
    if PYTHON2:
        profile(remove_chars_re_unicode)
    else:
        profile(remove_chars_re)
    
    profile(remove_chars_translate_unicode)
    

    2.7.5 (default, Mar  9 2014, 22:15:05) 
    [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
    
    "plain" string:
    
    0.637 remove_chars_iter
    0.649 remove_chars_re
    0.010 remove_chars_translate_bytes
    
    unicode string:
    
    0.866 remove_chars_iter
    0.680 remove_chars_re_unicode
    1.373 remove_chars_translate_unicode
    
    ---
    
    3.4.2 (v3.4.2:ab2c023a9432, Oct  5 2014, 20:42:22) 
    [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
    
    "plain" string:
    
    0.512 remove_chars_iter
    0.574 remove_chars_re
    0.765 remove_chars_translate_unicode
    
    unicode string:
    
    0.817 remove_chars_iter
    0.686 remove_chars_re
    0.876 remove_chars_translate_unicode
    

    remove_chars_translate_bytes