Tag Archive


amateur astronomy awk bash b[e] supergiant cartoon conference convert evolved star exoplanet fedora figaro fits fun galaxy history iraf large magellanic cloud latex linux lmc machine learning magellanic clouds massive star matplotlib meteor mypaper paper peblo photometry planet pro-am pyraf python red supergiant scisoft skinakas observatory small magellanic cloud smc spectroscopy starlink talk ubuntu university of crete video x-ray

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