Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for What Does the Cow Say? by Sim0000
COW = r'''
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
'''
MAXCHAR = 39
def cowsay(text):
# replace multiple spaces
while ' ' in text: text = text.replace(' ', ' ')
# make lines
lines = []
line = ''
for word in text.split(' '):
if len(word) > MAXCHAR: # we need divide the word
if line: # flush line
lines.append(line[:-1])
line = ''
while len(word) > MAXCHAR: # divide the word and append it
lines.append(word[:MAXCHAR])
word = word[MAXCHAR:]
if word: # the rest of the word
line += word + ' ' # append the rest of the word
else: # no divide case
if len(line) + len(word) > MAXCHAR: # flush line
lines.append(line[:-1])
line = ''
line += word + ' ' # append the word
if line: lines.append(line[:-1]) # flush line
# format output
n = len(lines)
maxlen = max(len(line) for line in lines)
s = '\n {}\n'.format('_' * (maxlen + 2))
for i in range(n):
border = ['||', '\\/', '/\\', '<>'][(2*(i == 0) + (i == n - 1))]
s += '{} {:{}} {}\n'.format(border[0], lines[i], maxlen, border[1])
return s + ' {}{}'.format('-' * (maxlen + 2), COW)
# line 40 is same as follows.
#
# if i == n - 1 == 0: border = '<>' # index = 3
# elif i == 0: border = '/\\' # index = 2
# elif i == n - 1: border = '\\/' # index = 1
# else: border = '||' # index = 0
#
May 27, 2014
Comments: