about Grigoris Maravelias
Replacing many characters in a string with Python

Replacing many characters in a string with Python

In order to replace a character in a string with Python replace command can be used easily: str.replace(old, new[, count])
[return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.]

But if we want to change more than one character then we have to do it differently. A nice solution I found at Gomputor’s blog is by defining a function like this:

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

So then we just have to give our string (text) and the list of changes (dic) like:st = '2011-05-23T22:31:35'
chgs = {'-':'','T':'.',':':''}

and use that function: >>>print st, replace_all(st,chgs)
2011-05-23T22:31:35 20110523.223135

Leave a Reply

Your email address will not be published. Required fields are marked *