From e73e4ca02d918822164c5b0892371e2c166814a0 Mon Sep 17 00:00:00 2001 From: Mahmoud Hashemi Date: Wed, 20 Feb 2013 01:51:36 -0800 Subject: [PATCH] add under2camel, camel2under, and slugify (and split_punct_ws, which is much faster than re-based punctuation splitting) --- boltons/strutils.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 boltons/strutils.py diff --git a/boltons/strutils.py b/boltons/strutils.py new file mode 100644 index 0000000..339023f --- /dev/null +++ b/boltons/strutils.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +import re +import string + +_camel2under_re = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))') +_punct_ws_str = string.punctuation + string.whitespace + + +def slugify(text, delim='_'): + return delim.join(split_punct_ws(text).lower()) + + +def split_punct_ws(text, _punct=_punct_ws_str): + return [w for w in text.split(_punct) if w] + + +def camel2under(string): + return _camel2under_re.sub(r'_\1', string).lower() + + +def under2camel(string): + return ''.join(w.capitalize() or '_' for w in string.split('_'))