How to print a string this way

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

For instance:

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

+4
source share
3 answers

How about this?

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

It works pretty fast. 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 
+9
source
 >>> 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:
Typically, a period matches all characters except newlines. Use re.S to match dots with all characters, including newlines.

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

+4
source
 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) 
+2
source

Source: https://habr.com/ru/post/1312726/


All Articles