Basic python question in Blog example

4 views
Skip to first unread message

Todd Williams

unread,
Oct 18, 2009, 6:02:47 PM10/18/09
to Tornado Web Server
I'm pretty new to python so I was wondering if someone could help
explain these two lines of code from the blog demo or at least tell me
if I am correct with my understanding.

# in an expression that starts with a word character replace spaces
with -
slug = re.sub(r"[^\w]+", " ", slug)
slug = "-".join(slug.lower().strip().split())

Am I right?

Andrew Gwozdziewycz

unread,
Oct 18, 2009, 6:07:26 PM10/18/09
to python-...@googlegroups.com

The idea here is to turn any string i.e. (This is my blog's title) and
turn it into this-is-my-blogs-title. This can be achieved by first
changing all of the non word characters to spaces. Then, split the
string up by space (string.split() defaults to splitting by " ") and
then joining it back together again with "-" in between them.

The only 2 pieces left are lower(), which makes the string lowercase, and
strip() which strips leading and trailing whitespace.

--
http://apgwoz.com

Todd Williams

unread,
Oct 18, 2009, 6:40:10 PM10/18/09
to Tornado Web Server
Thank You, now I get it! That brings up a new question: Is the
apostrophe considered a non word character? Wouldn't the example turn
it into either this-is-my-blog-s-title or this-is-my-blog's-title?
Which part of that removes the apostrophe?

Andrew Gwozdziewycz

unread,
Oct 18, 2009, 6:44:37 PM10/18/09
to python-...@googlegroups.com
On Sun, Oct 18, 2009 at 6:40 PM, Todd Williams <tod...@media1designs.com> wrote:
>
> Thank You, now I get it! That brings up a new question: Is the
> apostrophe considered a non word character?  Wouldn't the example turn
> it into either this-is-my-blog-s-title or this-is-my-blog's-title?

Yup, you're exactly write. Typo on my part. Sorry about that.


--
http://www.apgwoz.com

Reply all
Reply to author
Forward
0 new messages