简体   繁体   中英

Replacing special characters in Python

How can I replace these characters in Python2.7 with comma:

|

something like this does not work:

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

Thanks

Use Regular expression which contains list of characters to be replaced

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

SYNTAX:

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

This method replace all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided.

EDIT You have to declare at the top of source file that it uses Unicode literals.

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

Also prefix string being searched with u

a = u"6• 918417•12"
a = re.sub(u"[|•]", ",", a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM