From 9f1ab8713cf8c3362c45fca435ac60e0c91edaf8 Mon Sep 17 00:00:00 2001 From: Valentin Lab Date: Wed, 4 Feb 2015 19:05:46 +0700 Subject: [PATCH] new: added ``ucfirst`` and ``shorten``. --- README.rst | 22 ++++++++++++++++++++++ src/kids/txt/__init__.py | 2 +- src/kids/txt/txt.py | 16 ++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index e60868a..26b4875 100644 --- a/README.rst +++ b/README.rst @@ -112,6 +112,28 @@ Wrap paragraph separately:: Notice that that each paragraph has been wrapped separately. +ucfirst +------- + +This function will return the given string with the first character forced to +uppercase:: + + >>> txt.ucfirst('foo') + 'Foo' + + +shorten +------- + +This function will truncate the given string to the given length, if necessary. It'll +replace the last 2 characters by a '..' to indicate truncation:: + + >>> txt.shorten('fool', l=5) + 'fool' + >>> txt.shorten('supercalifragilisticexpialidocious', l=5) + 'sup..' + + Contributing ============ diff --git a/src/kids/txt/__init__.py b/src/kids/txt/__init__.py index 4ca40f9..adeb8a2 100644 --- a/src/kids/txt/__init__.py +++ b/src/kids/txt/__init__.py @@ -1,3 +1,3 @@ # Package placeholder -from .txt import indent, dedent, paragraph_wrap +from .txt import indent, dedent, paragraph_wrap, ucfirst, shorten diff --git a/src/kids/txt/txt.py b/src/kids/txt/txt.py index 83c2e52..809b00c 100644 --- a/src/kids/txt/txt.py +++ b/src/kids/txt/txt.py @@ -88,3 +88,19 @@ def paragraph_wrap(text, regexp="\n\n"): regexp = re.compile(regexp, re.MULTILINE) return "\n".join("\n".join(textwrap.wrap(paragraph.strip())) for paragraph in regexp.split(text)).strip() + + +def ucfirst(msg): + """Return altered msg where only first letter was forced to uppercase.""" + return msg[0].upper() + msg[1:] + + +## Provided in textwrap.shorten in python 3 +def shorten(s, l): + """Return given string truncated to given length.""" + if len(s) > l: + return s[:l - 2] + ".." + return s + + +truncate = shorten