对于每个字符串,我需要打印#每6个字符。
例如:
example_string = "this is an example string. ok ????"
myfunction(example_string)
"this i#s an e#xample# strin#g. ok #????"
最有效的方法是什么?
答案 0 :(得分:9)
这个怎么样?
'#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])
它也很快运行。在我的机器上,每100个字符的字符串为5微秒:
>>> import timeit
>>> timeit.Timer( "'#'.join([s[a:a+6] for a in range(0,len(s),6)])", "s='x'*100").timeit()
4.9556539058685303
答案 1 :(得分:4)
>>> str = "this is an example string. ok ????"
>>> import re
>>> re.sub("(.{6})", r"\1#", str)
'this i#s an e#xample# strin#g. ok #????'
更新:
通常,点匹配除换行之外的所有字符。使用re.S
使点匹配所有字符,包括换行字符。
>>> pattern = re.compile("(.{6})", re.S)
>>> str = "this is an example string with\nmore than one line\nin it. It has three lines"
>>> print pattern.sub(r"\1#", str)
this i#s an e#xample# strin#g with#
more #than o#ne lin#e
in i#t. It #has th#ree li#nes
答案 2 :(得分:2)
import itertools
def every6(sin, c='#'):
r = itertools.izip_longest(*([iter(sin)] * 6 + [c * (len(sin) // 6)]))
return ''.join(''.join(y for y in x if y is not None) for x in r)
print every6(example_string)