我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
当前回答
这个怎么样:
def text_cleanup(text):
new = ""
for i in text:
if i not in " ?.!/;:":
new += i
return new
其他回答
试试这个:
def rm_char(original_str, need2rm):
''' Remove charecters in "need2rm" from "original_str" '''
return original_str.translate(str.maketrans('','',need2rm))
这个方法在python3中很有效
即使是下面的方法也是有效的
line = "a,b,c,d,e"
alpha = list(line)
while ',' in alpha:
alpha.remove(',')
finalString = ''.join(alpha)
print(finalString)
输出:中的
您还可以使用函数来替换不同类型的正则表达式或使用列表的其他模式。这样,您就可以混合正则表达式、字符类和真正基本的文本模式。当您需要替换大量元素(如HTML元素)时,它非常有用。
*注意:适用于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)
在函数string_cleanup中,它以字符串x和未修饰的列表作为参数。对于元素或模式列表中的每一项,如果需要替代品,就会进行替换。
输出:
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
使用过滤器,你只需要一行
line = filter(lambda char: char not in " ?.!/;:", line)
这将字符串视为可迭代对象,如果lambda返回True,则检查每个字符:
> > >帮助(过滤器) 模块__builtin__中内置函数过滤器的帮助: 过滤器(…) filter(function或None, sequence) ->列表、元组或字符串 返回函数(item)为true的序列项。如果 函数为None,返回为true的项。If sequence是一个元组 或者字符串,返回相同的类型,否则返回一个列表。
令我惊讶的是,还没有人推荐使用内置的过滤功能。
import operator
import string # only for the example you could use a custom string
s = "1212edjaq"
假设我们想过滤掉所有不是数字的东西。使用过滤器内置方法“…等效于生成器表达式(item for item在可迭代if函数(item)中)"[Python 3 Builtins: Filter]
sList = list(s)
intsList = list(string.digits)
obj = filter(lambda x: operator.contains(intsList, x), sList)))
在Python 3中返回
>> <filter object @ hex>
要得到打印的字符串,
nums = "".join(list(obj))
print(nums)
>> "1212"
我不确定过滤器在效率方面的排名,但在做列表理解等时,知道如何使用是一件好事。
更新
从逻辑上讲,既然过滤器可以工作,你也可以使用列表理解,从我所读到的,它应该更有效,因为lambdas是编程函数世界的华尔街对冲基金经理。另一个优点是它是一个单行程序,不需要任何导入。例如,使用上面定义的字符串's',
num = "".join([i for i in s if i.isdigit()])
就是这样。返回值将是原始字符串中所有数字组成的字符串。
如果你有一个特定的可接受/不可接受字符列表,你只需要调整列表理解的' If '部分。
target_chars = "".join([i for i in s if i in some_list])
或者,
target_chars = "".join([i for i in s if i not in some_list])