以何种方式打印字符串?

4

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

例如:

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

myfunction(example_string)

"this i#s an e#xample# strin#g. ok #????"

什么是最有效的方式来做到这一点?
3个回答

9
这个怎么样?
'#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])

它的运行速度也非常快。在我的机器上,每100个字符字符串只需要五微秒:

>>> import timeit
>>> timeit.Timer( "'#'.join([s[a:a+6] for a in range(0,len(s),6)])", "s='x'*100").timeit()
4.9556539058685303

在Python 2.x中,使用xrange而不是range可能会更好。 - John Machin
除非你处理的是相当长的字符串,否则这不太可能有很大的区别。在我的计算机上,使用xrange()的差异只有几十万分之几秒。(这与Python 2.6文档中xrange()的说明相符。) - ʇsәɹoɈ

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)

这是一个带有多行文本的例子字符串。
它共有三行,每行都包含了一部分内容。
在其中,有些文字被标记为#号,需要注意。


1
re.DOTALL 标志,也称为 re.S(单行模式),翻转以使点匹配所有内容。请参见更新 @John。 - Amarghosh

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接