代码如下:
#encoding=utf-8
print '中国'
#简单字符串替换
str = 'abc'
print str.replace('a', 'one')
#根据字典内容,替换被标记的字符串
def expand(format,d,marker='"',safe=False): #safe 如果字典中找不到,不会抛出异常
if safe:
def lookup(w):return d.get(w,w.join(marker * 2))
else:
def lookup(w):return d[w]
parts = format.split(marker)
print parts #帮助理解打印
parts[1::2] = map(lookup,parts[1::2]) #经典的步长为2
return ''.join(parts)
print expand('just "a" test"a""a""a""a"',{'a':'one'})
print expand('just "b" test"b""b""b""b"',{'a':'one'},'"',True)
# print expand('just "b" test"b""b""b""b"',{'a':'one'},'"',False) 会抛出异常
打印结果如下:
中国
onebc
['just ', 'a', ' test', 'a', '', 'a', '', 'a', '', 'a', '']
just one testoneoneoneone
['just ', 'b', ' test', 'b', '', 'b', '', 'b', '', 'b', '']
just "b" test"b""b""b""b"