开发者

Python regex replace to create smiley faces

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

Hello th开发者_JAVA百科is 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?


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


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


Here is a re.sub oneliner as requested (split for clarity):

import re 

print re.sub( r'\w(\w?)(\w*)', \
              lambda m: '8'*len(m.group(1)) + '='*len(m.group(2)) + 'D', \
              "Hello this is a mighty fine day today" )


Here's your one-liner (sorry, no regex):

for word in sentence.split(' '): print '8' + '=' * (len(word) - 2) + 'D',


I don't think there is any reason to use regular expression as in the previous solutions. Try this instead:

def pen(string):
    return ' '.join([("%s%s%s"%('8','='*(len(word)-2),'D'))[-len(word):] \
         for word in string.split()])

It seems to work much faster than one of the regex ones that I chose arbitrarily.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜