Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex replace to create smiley faces

Tags:

python

regex

I'd like to create a regex string that would turn this text:

Hello this is a mighty fine day today

into

8===D 8==D 8D D 8====D 8==D 8=D 8===D

is this possible with a python re.sub oneliner?

like image 961
halconnen Avatar asked Jul 18 '11 18:07

halconnen


2 Answers

No need for regexes:

s = 'Hello this is a mighty fine day today'
' '.join('%s%sD'%('8' if len(w) > 1 else '', '='*(len(w)-2)) for w in s.split())
# '8===D 8==D 8D D 8====D 8==D 8=D 8===D'

Edit: debugged ;) Thanks for the pointer @tg

like image 91
mhyfritz Avatar answered Nov 02 '22 23:11

mhyfritz


The question is asking for a re.sub one-liner, so here is one that does the job:

In [1]: import re

In [2]: s = "Hello this is a mighty fine day today"
In [3]: print re.sub(r"\w+", lambda x:("8"+"="*1000)[:len(x.group())-1]+"D", s)
8===D 8==D 8D D 8====D 8==D 8=D 8===D

For educational purposes only! 8=D

like image 43
NPE Avatar answered Nov 03 '22 00:11

NPE