从Python中删除字符串中的特定字符。

时间:2022-12-29 20:21:47

I'm trying to remove specific characters from a string using Python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string.

我正在尝试用Python从一个字符串中删除特定的字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有任何作用。

for char in line:
    if char in " ?.!/;:":
        line.replace(char,'')

How do I do this properly?

我怎样才能正确地做到这一点呢?

23 个解决方案

#1


453  

Strings in Python are immutable (can't be changed). Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one. You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed.

Python中的字符串是不可变的(不能更改)。因此,line.replace(…)的作用只是创建一个新的字符串,而不是更改旧的字符串。您需要重新绑定(赋值)以使该变量接受新值,并删除这些字符。

Also, the way you are doing it is going to be kind of slow, relatively. It's also likely to be a bit confusing to experienced pythonators, who will see a doubly-nested structure and think for a moment that something more complicated is going on.

而且,你做的方式会比较慢。对于经验丰富的pythonators来说,它也可能会让人感到困惑,他们会看到一个双嵌套结构,并且会想一些更复杂的事情正在发生。

Starting in Python 2.6 and newer Python 2.x versions *, you can instead use str.translate, (but read on for Python 3 differences):

从Python 2.6和更新的Python 2开始。x版本*,您可以使用string .translate(但请阅读Python 3的差异):

line = line.translate(None, '!@#$')

or regular expression replacement with re.sub

或者正则表达式替换为re.sub。

import re
line = re.sub('[!@#$]', '', line)

The characters enclosed in brackets constitute a character class. Any characters in line which are in that class are replaced with the second parameter to sub: an empty string.

括号内的字符构成一个字符类。在该类中的任何字符都被替换为第二个参数:一个空字符串。

In Python 3, strings are Unicode. You'll have to translate a little differently. kevpie mentions this in a comment on one of the answers, and it's noted in the documentation for str.translate.

在Python 3中,字符串是Unicode。你需要做一些不同的翻译。kevpie在对其中一个答案的评论中提到了这一点,并在str.translate的文档中提到。

When calling the translate method of a Unicode string, you cannot pass the second parameter that we used above. You also can't pass None as the first parameter, or even a translation table from string.maketrans. Instead, you pass a dictionary as the only parameter. This dictionary maps the ordinal values of characters (i.e. the result of calling ord on them) to the ordinal values of the characters which should replace them, or—usefully to us—None to indicate that they should be deleted.

当调用Unicode字符串的翻译方法时,您不能传递我们上面使用的第二个参数。您也不能将None作为第一个参数,甚至不能通过string.maketrans来传递一个转换表。相反,您将一个字典作为惟一的参数。本字典将字符的序号值(即调用ord的结果)映射到应该替换它们的字符的序数值,或者对我们来说,没有表示它们应该被删除。

So to do the above dance with a Unicode string you would call something like

因此,使用Unicode字符串进行上述舞蹈,您可以调用类似的方法。

translation_table = dict.fromkeys(map(ord, '!@#$'), None)
unicode_line = unicode_line.translate(translation_table)

Here dict.fromkeys and map are used to succinctly generate a dictionary containing

这里的dict.fromkeys和map被用来简洁地生成一个包含的字典。

{ord('!'): None, ord('@'): None, ...}

Even simpler, as another answer puts it, create the dictionary in place:

甚至更简单,正如另一个答案所说,创建字典的地方:

unicode_line = unicode_line.translate({ord(c): None for c in '!@#$'})

* for compatibility with earlier Pythons, you can create a "null" translation table to pass in place of None:

*为了与早期的python兼容,您可以创建一个“null”转换表,以代替None:

import string
line = line.translate(string.maketrans('', ''), '!@#$')

Here string.maketrans is used to create a translation table, which is just a string containing the characters with ordinal values 0 to 255.

这里的字符串。maketrans用来创建一个转换表,它只是一个字符串,其中包含的字符值为0到255。

#2


140  

Am I missing the point here, or is it just the following:

是我忽略了这一点,还是仅仅是以下几点:

>>> string = "ab1cd1ef"
>>> string.replace("1","")
'abcdef'
>>>

Put it in a loop:

把它放在一个循环中:

>>>
>>> a = "a!b@c#d$"
>>> b = "!@#$"
>>> for char in b:
...     a = a.replace(char,"")
...
>>> print a
abcd
>>>

#3


29  

>>> line = "abc#@!?efg12;:?"
>>> ''.join( c for c in line if  c not in '?:!/;' )
'abc#@efg12'

#4


16  

The asker almost had it. Like most things in Python, the answer is simpler than you think.

阿斯克几乎要了。和Python里的大多数东西一样,答案比你想象的要简单。

>>> line = "H E?.LL!/;O:: "  
>>> for char in ' ?.!/;:':  
...  line = line.replace(char,'')  
...
>>> print line
HELLO

You don't have to do the nested if/for loop thing, but you DO need to check each character individually.

你不需要做嵌套的if/for循环,但是你需要逐个检查每个字符。

#5


16  

For the inverse requirement of only allowing certain characters in a string, you can use regular expressions with a set complement operator [^ABCabc]. For example, to remove everything except ascii letters, digits, and the hyphen:

的逆要求只允许特定的字符串中的字符,您可以使用正则表达式使用一组补算子(^ ABCabc]。例如,除ascii字母、数字和连字符外,删除所有内容:

>>> import string
>>> import re
>>>
>>> phrase = '  There were "nine" (9) chick-peas in my pocket!!!      '
>>> allow = string.letters + string.digits + '-'
>>> re.sub('[^%s]' % allow, '', phrase)

'Therewerenine9chick-peasinmypocket'

From the python regular expression documentation:

从python的正则表达式文档中:

Characters that are not within a range can be matched by complementing the set. If the first character of the set is '^', all the characters that are not in the set will be matched. For example, [^5] will match any character except '5', and [^^] will match any character except '^'. ^ has no special meaning if it’s not the first character in the set.

字符不可以匹配范围内补充。如果第一个字符是“^”,不是所有的人物的设置将会匹配。例如,[5]将匹配除“5”以外的任何字符,[]将匹配除“”以外的任何字符。^没有特殊的意思如果不是第一个字符的集合。

#6


15  

line = line.translate(None, " ?.!/;:")

#7


11  

Easy peasy with re.sub in Python 3.5

re.sub('\ |\?|\.|\!|\/|\;|\:', '', line)

Example

>>> import re

>>> line = 'Q: Do I write ;/.??? No!!!'

>>> re.sub('\ |\?|\.|\!|\/|\;|\:', '', line)
'QDoIwriteNo'

Explanation

In regular expressions (regex), | is a logical OR and \ escapes spaces and special characters that might be actual regex commands. sub stands for substitution.

在正则表达式(regex)中,|是一个逻辑的或\ \逃离空间和特殊字符,可能是实际的regex命令。子代表替换。

#8


10  

>>> s = 'a1b2c3'
>>> ''.join(c for c in s if c not in '123')
'abc'

#9


7  

Strings are immutable in Python. The replace method returns a new string after the replacement. Try:

字符串在Python中是不可变的。replace方法在替换后返回一个新字符串。试一试:

for char in line:
    if char in " ?.!/;:":
        line = line.replace(char,'')

#10


4  

Using filter, you'd just need one line

使用过滤器,您只需要一行。

line = filter(lambda char: char not in " ?.!/;:", line)

This treats the string as an iterable and checks every character if the lambda returns True:

这将字符串视为可迭代的并检查每个字符,如果lambda返回True:

>>> help(filter)
Help on built-in function filter in module __builtin__:

filter(...)
    filter(function or None, sequence) -> list, tuple, or string

    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.

#11


4  

I was surprised that no one had yet recommended using the builtin filter function.

我很惊讶,没有人推荐使用builtin filter函数。

    import operator
    import string # only for the example you could use a custom string

    s = "1212edjaq"

Say we want to filter out everything that isn't a number. Using the filter builtin method "...is equivalent to the generator expression (item for item in iterable if function(item))" [Python 3 Builtins: Filter]

说我们想过滤掉所有不是数字的东西。使用过滤器构建方法“……”等效于生成器表达式(如果函数(项),则可以在iterable中进行项)。(Python 3内置过滤器):

    sList = list(s)
    intsList = list(string.digits)
    obj = filter(lambda x: operator.contains(intsList, x), sList)))

In Python 3 this returns

在Python 3中,此返回。

    >>  <filter object @ hex>

To get a printed string,

为了得到一个打印的字符串,

    nums = "".join(list(obj))
    print(nums)
    >> "1212"

I am not sure how filter ranks in terms of efficiency but it is a good thing to know how to use when doing list comprehensions and such.

我不确定过滤器在效率方面的排名如何,但是知道如何使用列表的理解是一件很好的事情。

UPDATE

更新

Logically, since filter works you could also use list comprehension and from what I have read it is supposed to be more efficient because lambdas are the wall street hedge fund managers of the programming function world. Another plus is that it is a one-liner that doesnt require any imports. For example, using the same string 's' defined above,

从逻辑上讲,由于过滤器的作用,你也可以使用列表的理解,而我读过的内容应该更有效,因为lambdas是编程函数世界的华尔街对冲基金经理。另一个优点是,它是一种不需要任何进口的单行。例如,使用上述相同的字符串's',

      num = "".join([i for i in s if i.isdigit()])

That's it. The return will be a string of all the characters that are digits in the original string.

就是这样。返回将是一个字符串,所有字符都是原始字符串中的数字。

If you have a specific list of acceptable/unacceptable characters you need only adjust the 'if' part of the list comprehension.

如果您有一个特定的可接受/不能接受的字符列表,您只需要调整列表理解中的“If”部分。

      target_chars = "".join([i for i in s if i in some_list]) 

or alternatively,

或者,

      target_chars = "".join([i for i in s if i not in some_list])

#12


4  

>>> # Character stripping
>>> a = '?abcd1234!!'
>>> t.lstrip('?')
'abcd1234!!'
>>> t.strip('?!')
'abcd1234'

#13


3  

Here's my Python 2/3 compatible version. Since the translate api has changed.

这是我的Python 2/3兼容版本。因为翻译api已经改变了。

def remove(str_, chars):
    """Removes each char in `chars` from `str_`.

    Args:
        str_: String to remove characters from
        chars: String of to-be removed characters

    Returns:
        A copy of str_ with `chars` removed

    Example:
            remove("What?!?: darn;", " ?.!:;") => 'Whatdarn'
    """
    try:
        # Python2.x
        return str_.translate(None, chars)
    except TypeError:
        # Python 3.x
        table = {ord(char): None for char in chars}
        return str_.translate(table)

#14


2  

#!/usr/bin/python
import re

strs = "how^ much for{} the maple syrup? $20.99? That's[] ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!|a|b]',r' ',strs)#i have taken special character to remove but any #character can be added here
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)#for removing special character
print nestr

#15


2  

How about this:

这个怎么样:

def text_cleanup(text):
    new = ""
    for i in text:
        if i not in " ?.!/;:":
            new += i
    return new

#16


1  

Below one.. with out using regular expression concept..

下面一个. .使用正则表达式概念。

ipstring ="text with symbols!@#$^&*( ends here"
opstring=''
for i in ipstring:
    if i.isalnum()==1 or i==' ':
        opstring+=i
    pass
print opstring

#17


1  

You can also use a function in order to substitute different kind of regular expression or other pattern with the use of a list. With that, you can mixed regular expression, character class, and really basic text pattern. It's really useful when you need to substitute a lot of elements like HTML ones.

您还可以使用一个函数来替换不同类型的正则表达式或其他使用列表的模式。这样,您可以混合正则表达式、字符类和真正的基本文本模式。当您需要替换许多元素(比如HTML)时,它非常有用。

*NB: works with Python 3.x

*NB:使用Python 3.x。

import re  # Regular expression library


def string_cleanup(x, notwanted):
    for item in notwanted:
        x = re.sub(item, '', x)
    return x

line = "<title>My example: <strong>A text %very% $clean!!</strong></title>"
print("Uncleaned: ", line)

# Get rid of html elements
html_elements = ["<title>", "</title>", "<strong>", "</strong>"]
line = string_cleanup(line, html_elements)
print("1st clean: ", line)

# Get rid of special characters
special_chars = ["[!@#$]", "%"]
line = string_cleanup(line, special_chars)
print("2nd clean: ", line)

In the function string_cleanup, it takes your string x and your list notwanted as arguments. For each item in that list of elements or pattern, if a substitute is needed it will be done.

在函数string_cleanup中,它将字符串x和列表notwanted作为参数。对于元素或模式列表中的每一项,如果需要替换,就会完成。

The output:

输出:

Uncleaned:  <title>My example: <strong>A text %very% $clean!!</strong></title>
1st clean:  My example: A text %very% $clean!!
2nd clean:  My example: A text very clean

#18


1  

My method I'd use probably wouldn't work as efficiently, but it is massively simple. I can remove multiple characters at different positions all at once, using slicing and formatting. Here's an example:

我使用的方法可能不会有效,但它非常简单。我可以一次删除多个字符在不同的位置,使用切片和格式化。这里有一个例子:

words = "things"
removed = "%s%s" % (words[:3], words[-1:])

This will result in 'removed' holding the word 'this'.

这将导致“移除”这个词。

Formatting can be very helpful for printing variables midway through a print string. It can insert any data type using a % followed by the variable's data type; all data types can use %s, and floats (aka decimals) and integers can use %d.

格式化可以非常有助于在打印字符串的中途打印变量。它可以使用%后跟变量的数据类型插入任何数据类型;所有数据类型都可以使用%s,浮动(也称为小数)和整数可以使用%d。

Slicing can be used for intricate control over strings. When I put words[:3], it allows me to select all the characters in the string from the beginning (the colon is before the number, this will mean 'from the beginning to') to the 4th character (it includes the 4th character). The reason 3 equals till the 4th position is because Python starts at 0. Then, when I put word[-1:], it means the 2nd last character to the end (the colon is behind the number). Putting -1 will make Python count from the last character, rather than the first. Again, Python will start at 0. So, word[-1:] basically means 'from the second last character to the end of the string.

切片可用于复杂的字符串控制。当我输入单词[:3]时,它允许我从一开始就选择字符串中的所有字符(冒号是在数字之前,这将意味着“从开始到”)到第4个字符(它包括第4个字符)。原因3等于直到第4位,因为Python从0开始。然后,当我输入单词[-1:]时,它表示最后一个字符到末尾(冒号在数字后面)。put -1将使Python从最后一个字符开始计数,而不是第一个字符。同样,Python将从0开始。所以,word[-1:]基本上是指从第二个字符到字符串的末尾。

So, by cutting off the characters before the character I want to remove and the characters after and sandwiching them together, I can remove the unwanted character. Think of it like a sausage. In the middle it's dirty, so I want to get rid of it. I simply cut off the two ends I want then put them together without the unwanted part in the middle.

因此,在删除角色之前,我想删除字符,然后将它们放在一起,我可以删除不需要的字符。把它想象成香肠。在中间它很脏,所以我想把它处理掉。我只是把我想要的两端切下来,然后把它们放在一起,而不需要中间的部分。

If I want to remove multiple consecutive characters, I simply shift the numbers around in the [] (slicing part). Or if I want to remove multiple characters from different positions, I can simply sandwich together multiple slices at once.

如果我想要删除多个连续字符,我只需在[](切片部分)中移动数字。或者,如果我想要从不同的位置删除多个字符,我可以简单地将多个片组合在一起。

Examples:

例子:

 words = "control"
 removed = "%s%s" % (words[:2], words[-2:])

removed equals 'cool'.

删除=“酷”。

words = "impacts"
removed = "%s%s%s" % (words[1], words[3:5], words[-1])

removed equals 'macs'.

删除=“巨无霸”。

In this case, [3:5] means character at position 3 through character at position 5 (excluding the character at the final position).

在这种情况下,[3:5]意味着角色在位置3的角色在位置5(不包括在最后位置的字符)。

Remember, Python starts counting at 0, so you will need to as well.

请记住,Python开始计数为0,因此您也需要这样做。

#19


1  

In Python 3.5

e.g.,

例如,

os.rename(file_name, file_name.translate({ord(c): None for c in '0123456789'}))

To remove all the number from the string

从字符串中删除所有数字。

#20


1  

you can use set

您可以使用集

    charlist = list(set(string.digits+string.ascii_uppercase) - set('10IO'))
    return ''.join([random.SystemRandom().choice(charlist) for _ in range(passlen)])

#21


1  

Recursive split: s=string ; chars=chars to remove

递归分割:s =字符串;识字课=字符删除

def strip(s,chars):
if len(s)==1:
    return "" if s in chars else s
return strip(s[0:int(len(s)/2)],chars) +  strip(s[int(len(s)/2):len(s)],chars)

example:

例子:

print(strip("Hello!","lo"))    #He!

#22


1  

Even the below approach works

甚至下面的方法也有效。

line = "a,b,c,d,e"
alpha = list(line)
        while ',' in alpha:
            alpha.remove(',')
finalString = ''.join(alpha)
print(finalString)

output >> abcde

> >中的输出

#23


0  

Try this one:

试试这个:

def rm_char(original_str, need2rm):
    ''' Remove charecters in "need2rm" from "original_str" '''
    return original_str.translate(str.maketrans('','',need2rm))

This method works well in python 3.5.2

该方法在python 3.5.2中运行良好。

#1


453  

Strings in Python are immutable (can't be changed). Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one. You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed.

Python中的字符串是不可变的(不能更改)。因此,line.replace(…)的作用只是创建一个新的字符串,而不是更改旧的字符串。您需要重新绑定(赋值)以使该变量接受新值,并删除这些字符。

Also, the way you are doing it is going to be kind of slow, relatively. It's also likely to be a bit confusing to experienced pythonators, who will see a doubly-nested structure and think for a moment that something more complicated is going on.

而且,你做的方式会比较慢。对于经验丰富的pythonators来说,它也可能会让人感到困惑,他们会看到一个双嵌套结构,并且会想一些更复杂的事情正在发生。

Starting in Python 2.6 and newer Python 2.x versions *, you can instead use str.translate, (but read on for Python 3 differences):

从Python 2.6和更新的Python 2开始。x版本*,您可以使用string .translate(但请阅读Python 3的差异):

line = line.translate(None, '!@#$')

or regular expression replacement with re.sub

或者正则表达式替换为re.sub。

import re
line = re.sub('[!@#$]', '', line)

The characters enclosed in brackets constitute a character class. Any characters in line which are in that class are replaced with the second parameter to sub: an empty string.

括号内的字符构成一个字符类。在该类中的任何字符都被替换为第二个参数:一个空字符串。

In Python 3, strings are Unicode. You'll have to translate a little differently. kevpie mentions this in a comment on one of the answers, and it's noted in the documentation for str.translate.

在Python 3中,字符串是Unicode。你需要做一些不同的翻译。kevpie在对其中一个答案的评论中提到了这一点,并在str.translate的文档中提到。

When calling the translate method of a Unicode string, you cannot pass the second parameter that we used above. You also can't pass None as the first parameter, or even a translation table from string.maketrans. Instead, you pass a dictionary as the only parameter. This dictionary maps the ordinal values of characters (i.e. the result of calling ord on them) to the ordinal values of the characters which should replace them, or—usefully to us—None to indicate that they should be deleted.

当调用Unicode字符串的翻译方法时,您不能传递我们上面使用的第二个参数。您也不能将None作为第一个参数,甚至不能通过string.maketrans来传递一个转换表。相反,您将一个字典作为惟一的参数。本字典将字符的序号值(即调用ord的结果)映射到应该替换它们的字符的序数值,或者对我们来说,没有表示它们应该被删除。

So to do the above dance with a Unicode string you would call something like

因此,使用Unicode字符串进行上述舞蹈,您可以调用类似的方法。

translation_table = dict.fromkeys(map(ord, '!@#$'), None)
unicode_line = unicode_line.translate(translation_table)

Here dict.fromkeys and map are used to succinctly generate a dictionary containing

这里的dict.fromkeys和map被用来简洁地生成一个包含的字典。

{ord('!'): None, ord('@'): None, ...}

Even simpler, as another answer puts it, create the dictionary in place:

甚至更简单,正如另一个答案所说,创建字典的地方:

unicode_line = unicode_line.translate({ord(c): None for c in '!@#$'})

* for compatibility with earlier Pythons, you can create a "null" translation table to pass in place of None:

*为了与早期的python兼容,您可以创建一个“null”转换表,以代替None:

import string
line = line.translate(string.maketrans('', ''), '!@#$')

Here string.maketrans is used to create a translation table, which is just a string containing the characters with ordinal values 0 to 255.

这里的字符串。maketrans用来创建一个转换表,它只是一个字符串,其中包含的字符值为0到255。

#2


140  

Am I missing the point here, or is it just the following:

是我忽略了这一点,还是仅仅是以下几点:

>>> string = "ab1cd1ef"
>>> string.replace("1","")
'abcdef'
>>>

Put it in a loop:

把它放在一个循环中:

>>>
>>> a = "a!b@c#d$"
>>> b = "!@#$"
>>> for char in b:
...     a = a.replace(char,"")
...
>>> print a
abcd
>>>

#3


29  

>>> line = "abc#@!?efg12;:?"
>>> ''.join( c for c in line if  c not in '?:!/;' )
'abc#@efg12'

#4


16  

The asker almost had it. Like most things in Python, the answer is simpler than you think.

阿斯克几乎要了。和Python里的大多数东西一样,答案比你想象的要简单。

>>> line = "H E?.LL!/;O:: "  
>>> for char in ' ?.!/;:':  
...  line = line.replace(char,'')  
...
>>> print line
HELLO

You don't have to do the nested if/for loop thing, but you DO need to check each character individually.

你不需要做嵌套的if/for循环,但是你需要逐个检查每个字符。

#5


16  

For the inverse requirement of only allowing certain characters in a string, you can use regular expressions with a set complement operator [^ABCabc]. For example, to remove everything except ascii letters, digits, and the hyphen:

的逆要求只允许特定的字符串中的字符,您可以使用正则表达式使用一组补算子(^ ABCabc]。例如,除ascii字母、数字和连字符外,删除所有内容:

>>> import string
>>> import re
>>>
>>> phrase = '  There were "nine" (9) chick-peas in my pocket!!!      '
>>> allow = string.letters + string.digits + '-'
>>> re.sub('[^%s]' % allow, '', phrase)

'Therewerenine9chick-peasinmypocket'

From the python regular expression documentation:

从python的正则表达式文档中:

Characters that are not within a range can be matched by complementing the set. If the first character of the set is '^', all the characters that are not in the set will be matched. For example, [^5] will match any character except '5', and [^^] will match any character except '^'. ^ has no special meaning if it’s not the first character in the set.

字符不可以匹配范围内补充。如果第一个字符是“^”,不是所有的人物的设置将会匹配。例如,[5]将匹配除“5”以外的任何字符,[]将匹配除“”以外的任何字符。^没有特殊的意思如果不是第一个字符的集合。

#6


15  

line = line.translate(None, " ?.!/;:")

#7


11  

Easy peasy with re.sub in Python 3.5

re.sub('\ |\?|\.|\!|\/|\;|\:', '', line)

Example

>>> import re

>>> line = 'Q: Do I write ;/.??? No!!!'

>>> re.sub('\ |\?|\.|\!|\/|\;|\:', '', line)
'QDoIwriteNo'

Explanation

In regular expressions (regex), | is a logical OR and \ escapes spaces and special characters that might be actual regex commands. sub stands for substitution.

在正则表达式(regex)中,|是一个逻辑的或\ \逃离空间和特殊字符,可能是实际的regex命令。子代表替换。

#8


10  

>>> s = 'a1b2c3'
>>> ''.join(c for c in s if c not in '123')
'abc'

#9


7  

Strings are immutable in Python. The replace method returns a new string after the replacement. Try:

字符串在Python中是不可变的。replace方法在替换后返回一个新字符串。试一试:

for char in line:
    if char in " ?.!/;:":
        line = line.replace(char,'')

#10


4  

Using filter, you'd just need one line

使用过滤器,您只需要一行。

line = filter(lambda char: char not in " ?.!/;:", line)

This treats the string as an iterable and checks every character if the lambda returns True:

这将字符串视为可迭代的并检查每个字符,如果lambda返回True:

>>> help(filter)
Help on built-in function filter in module __builtin__:

filter(...)
    filter(function or None, sequence) -> list, tuple, or string

    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.

#11


4  

I was surprised that no one had yet recommended using the builtin filter function.

我很惊讶,没有人推荐使用builtin filter函数。

    import operator
    import string # only for the example you could use a custom string

    s = "1212edjaq"

Say we want to filter out everything that isn't a number. Using the filter builtin method "...is equivalent to the generator expression (item for item in iterable if function(item))" [Python 3 Builtins: Filter]

说我们想过滤掉所有不是数字的东西。使用过滤器构建方法“……”等效于生成器表达式(如果函数(项),则可以在iterable中进行项)。(Python 3内置过滤器):

    sList = list(s)
    intsList = list(string.digits)
    obj = filter(lambda x: operator.contains(intsList, x), sList)))

In Python 3 this returns

在Python 3中,此返回。

    >>  <filter object @ hex>

To get a printed string,

为了得到一个打印的字符串,

    nums = "".join(list(obj))
    print(nums)
    >> "1212"

I am not sure how filter ranks in terms of efficiency but it is a good thing to know how to use when doing list comprehensions and such.

我不确定过滤器在效率方面的排名如何,但是知道如何使用列表的理解是一件很好的事情。

UPDATE

更新

Logically, since filter works you could also use list comprehension and from what I have read it is supposed to be more efficient because lambdas are the wall street hedge fund managers of the programming function world. Another plus is that it is a one-liner that doesnt require any imports. For example, using the same string 's' defined above,

从逻辑上讲,由于过滤器的作用,你也可以使用列表的理解,而我读过的内容应该更有效,因为lambdas是编程函数世界的华尔街对冲基金经理。另一个优点是,它是一种不需要任何进口的单行。例如,使用上述相同的字符串's',

      num = "".join([i for i in s if i.isdigit()])

That's it. The return will be a string of all the characters that are digits in the original string.

就是这样。返回将是一个字符串,所有字符都是原始字符串中的数字。

If you have a specific list of acceptable/unacceptable characters you need only adjust the 'if' part of the list comprehension.

如果您有一个特定的可接受/不能接受的字符列表,您只需要调整列表理解中的“If”部分。

      target_chars = "".join([i for i in s if i in some_list]) 

or alternatively,

或者,

      target_chars = "".join([i for i in s if i not in some_list])

#12


4  

>>> # Character stripping
>>> a = '?abcd1234!!'
>>> t.lstrip('?')
'abcd1234!!'
>>> t.strip('?!')
'abcd1234'

#13


3  

Here's my Python 2/3 compatible version. Since the translate api has changed.

这是我的Python 2/3兼容版本。因为翻译api已经改变了。

def remove(str_, chars):
    """Removes each char in `chars` from `str_`.

    Args:
        str_: String to remove characters from
        chars: String of to-be removed characters

    Returns:
        A copy of str_ with `chars` removed

    Example:
            remove("What?!?: darn;", " ?.!:;") => 'Whatdarn'
    """
    try:
        # Python2.x
        return str_.translate(None, chars)
    except TypeError:
        # Python 3.x
        table = {ord(char): None for char in chars}
        return str_.translate(table)

#14


2  

#!/usr/bin/python
import re

strs = "how^ much for{} the maple syrup? $20.99? That's[] ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!|a|b]',r' ',strs)#i have taken special character to remove but any #character can be added here
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)#for removing special character
print nestr

#15


2  

How about this:

这个怎么样:

def text_cleanup(text):
    new = ""
    for i in text:
        if i not in " ?.!/;:":
            new += i
    return new

#16


1  

Below one.. with out using regular expression concept..

下面一个. .使用正则表达式概念。

ipstring ="text with symbols!@#$^&*( ends here"
opstring=''
for i in ipstring:
    if i.isalnum()==1 or i==' ':
        opstring+=i
    pass
print opstring

#17


1  

You can also use a function in order to substitute different kind of regular expression or other pattern with the use of a list. With that, you can mixed regular expression, character class, and really basic text pattern. It's really useful when you need to substitute a lot of elements like HTML ones.

您还可以使用一个函数来替换不同类型的正则表达式或其他使用列表的模式。这样,您可以混合正则表达式、字符类和真正的基本文本模式。当您需要替换许多元素(比如HTML)时,它非常有用。

*NB: works with Python 3.x

*NB:使用Python 3.x。

import re  # Regular expression library


def string_cleanup(x, notwanted):
    for item in notwanted:
        x = re.sub(item, '', x)
    return x

line = "<title>My example: <strong>A text %very% $clean!!</strong></title>"
print("Uncleaned: ", line)

# Get rid of html elements
html_elements = ["<title>", "</title>", "<strong>", "</strong>"]
line = string_cleanup(line, html_elements)
print("1st clean: ", line)

# Get rid of special characters
special_chars = ["[!@#$]", "%"]
line = string_cleanup(line, special_chars)
print("2nd clean: ", line)

In the function string_cleanup, it takes your string x and your list notwanted as arguments. For each item in that list of elements or pattern, if a substitute is needed it will be done.

在函数string_cleanup中,它将字符串x和列表notwanted作为参数。对于元素或模式列表中的每一项,如果需要替换,就会完成。

The output:

输出:

Uncleaned:  <title>My example: <strong>A text %very% $clean!!</strong></title>
1st clean:  My example: A text %very% $clean!!
2nd clean:  My example: A text very clean

#18


1  

My method I'd use probably wouldn't work as efficiently, but it is massively simple. I can remove multiple characters at different positions all at once, using slicing and formatting. Here's an example:

我使用的方法可能不会有效,但它非常简单。我可以一次删除多个字符在不同的位置,使用切片和格式化。这里有一个例子:

words = "things"
removed = "%s%s" % (words[:3], words[-1:])

This will result in 'removed' holding the word 'this'.

这将导致“移除”这个词。

Formatting can be very helpful for printing variables midway through a print string. It can insert any data type using a % followed by the variable's data type; all data types can use %s, and floats (aka decimals) and integers can use %d.

格式化可以非常有助于在打印字符串的中途打印变量。它可以使用%后跟变量的数据类型插入任何数据类型;所有数据类型都可以使用%s,浮动(也称为小数)和整数可以使用%d。

Slicing can be used for intricate control over strings. When I put words[:3], it allows me to select all the characters in the string from the beginning (the colon is before the number, this will mean 'from the beginning to') to the 4th character (it includes the 4th character). The reason 3 equals till the 4th position is because Python starts at 0. Then, when I put word[-1:], it means the 2nd last character to the end (the colon is behind the number). Putting -1 will make Python count from the last character, rather than the first. Again, Python will start at 0. So, word[-1:] basically means 'from the second last character to the end of the string.

切片可用于复杂的字符串控制。当我输入单词[:3]时,它允许我从一开始就选择字符串中的所有字符(冒号是在数字之前,这将意味着“从开始到”)到第4个字符(它包括第4个字符)。原因3等于直到第4位,因为Python从0开始。然后,当我输入单词[-1:]时,它表示最后一个字符到末尾(冒号在数字后面)。put -1将使Python从最后一个字符开始计数,而不是第一个字符。同样,Python将从0开始。所以,word[-1:]基本上是指从第二个字符到字符串的末尾。

So, by cutting off the characters before the character I want to remove and the characters after and sandwiching them together, I can remove the unwanted character. Think of it like a sausage. In the middle it's dirty, so I want to get rid of it. I simply cut off the two ends I want then put them together without the unwanted part in the middle.

因此,在删除角色之前,我想删除字符,然后将它们放在一起,我可以删除不需要的字符。把它想象成香肠。在中间它很脏,所以我想把它处理掉。我只是把我想要的两端切下来,然后把它们放在一起,而不需要中间的部分。

If I want to remove multiple consecutive characters, I simply shift the numbers around in the [] (slicing part). Or if I want to remove multiple characters from different positions, I can simply sandwich together multiple slices at once.

如果我想要删除多个连续字符,我只需在[](切片部分)中移动数字。或者,如果我想要从不同的位置删除多个字符,我可以简单地将多个片组合在一起。

Examples:

例子:

 words = "control"
 removed = "%s%s" % (words[:2], words[-2:])

removed equals 'cool'.

删除=“酷”。

words = "impacts"
removed = "%s%s%s" % (words[1], words[3:5], words[-1])

removed equals 'macs'.

删除=“巨无霸”。

In this case, [3:5] means character at position 3 through character at position 5 (excluding the character at the final position).

在这种情况下,[3:5]意味着角色在位置3的角色在位置5(不包括在最后位置的字符)。

Remember, Python starts counting at 0, so you will need to as well.

请记住,Python开始计数为0,因此您也需要这样做。

#19


1  

In Python 3.5

e.g.,

例如,

os.rename(file_name, file_name.translate({ord(c): None for c in '0123456789'}))

To remove all the number from the string

从字符串中删除所有数字。

#20


1  

you can use set

您可以使用集

    charlist = list(set(string.digits+string.ascii_uppercase) - set('10IO'))
    return ''.join([random.SystemRandom().choice(charlist) for _ in range(passlen)])

#21


1  

Recursive split: s=string ; chars=chars to remove

递归分割:s =字符串;识字课=字符删除

def strip(s,chars):
if len(s)==1:
    return "" if s in chars else s
return strip(s[0:int(len(s)/2)],chars) +  strip(s[int(len(s)/2):len(s)],chars)

example:

例子:

print(strip("Hello!","lo"))    #He!

#22


1  

Even the below approach works

甚至下面的方法也有效。

line = "a,b,c,d,e"
alpha = list(line)
        while ',' in alpha:
            alpha.remove(',')
finalString = ''.join(alpha)
print(finalString)

output >> abcde

> >中的输出

#23


0  

Try this one:

试试这个:

def rm_char(original_str, need2rm):
    ''' Remove charecters in "need2rm" from "original_str" '''
    return original_str.translate(str.maketrans('','',need2rm))

This method works well in python 3.5.2

该方法在python 3.5.2中运行良好。