只是为了学术。
尝试使用尽可能多的迭代器。
s = 'e6b693e6a0abe699ab'
from itertools import islice, izip, cycle, chain
def percentEncode(s):
percentChars = cycle('%')
firstChars = islice(s,0,None, 2)
secondChars = islice(s,1,None, 2)
return ''.join(chain.from_iterable(izip(percentChars, firstChars, secondChars)))
if __name__ == '__main__':
print percentEncode(s)
感谢 @tcarobruce 提醒重用字符串 iter。
s = 'e6b693e6a0abe699ab'
from itertools import islice, izip, cycle, chain
def percentEncode(s):
iter_s = iter(s)
return ''.join(chain.from_iterable(izip(cycle('%'), iter_s, iter_s)))
if __name__ == '__main__':
print percentEncode(s)