xRobot
xRobot

Reputation: 26567

How to print string in this way

For every string, I need to print # each 6 characters.

For example:

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

myfunction(example_string)

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

What is the most efficient way to do that ?

Upvotes: 3

Views: 244

Answers (3)

ʇsәɹoɈ
ʇsәɹoɈ

Reputation: 23459

How about this?

'#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])

It runs pretty quickly, too. On my machine, five microseconds per 100-character string:

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

Upvotes: 9

Amarghosh
Amarghosh

Reputation: 59451

>>> str = "this is an example string. ok ????"
>>> import re
>>> re.sub("(.{6})", r"\1#", str)
'this i#s an e#xample# strin#g. ok #????'

Update:
Normally dot matches all characters except new-lines. Use re.S to make dot match all characters including new-line chars.

>>> 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

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

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)

Upvotes: 2

Related Questions