如何以这种方式打印字符串

xRo*_*bot 4 python regex

对于每个字符串,我需要打印#每6个字符.

例如:

example_string = "this is an example string. ok ????"

myfunction(example_string)

"this i#s an e#xample# strin#g. ok #????"
Run Code Online (Sandbox Code Playgroud)

最有效的方法是什么?

ʇsә*_*ɹoɈ 9

这个怎么样?

'#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])
Run Code Online (Sandbox Code Playgroud)

它运行得非常快.在我的机器上,每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
Run Code Online (Sandbox Code Playgroud)