替换Python中的特殊字符

时间:2012-11-21 11:03:53

标签: python

如何用逗号代替Python2.7中的这些字符:

| •

这样的事情不起作用:

a= b.replace("|", ",")

由于

1 个答案:

答案 0 :(得分:3)

使用正则表达式,其中包含要替换的字符列表

import re
a = re.sub(u'[|•]', ',', a)

<强>语法:

re.sub(pattern, repl, string, max=0)

此方法用repl替换字符串中所有出现的RE模式,替换所有出现,除非提供 max

EDIT 您必须在源文件的顶部声明它使用Unicode文字。

# -*- coding: utf-8 -*-

还使用 u

搜索前缀字符串
a = u"6• 918417•12"
a = re.sub(u"[|•]", ",", a)