Popular Python recipes tagged "string"http://code.activestate.com/recipes/langs/python/tags/string/2015-01-24T21:21:27-08:00ActiveState Code RecipesBytes-to-human / human-to-bytes converter (Python)
2012-02-02T16:09:52-08:00Giampaolo Rodolàhttp://code.activestate.com/recipes/users/4178764/http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/
<p style="color: grey">
Python
recipe 578019
by <a href="/recipes/users/4178764/">Giampaolo Rodolà</a>
(<a href="/recipes/tags/bytes/">bytes</a>, <a href="/recipes/tags/conversion/">conversion</a>, <a href="/recipes/tags/converter/">converter</a>, <a href="/recipes/tags/human/">human</a>, <a href="/recipes/tags/humanize/">humanize</a>, <a href="/recipes/tags/string/">string</a>).
Revision 15.
</p>
<p>Here goes.</p>
Use PrettyTable and xtopdf to create PDF tables with borders, alignment and padding (Python)
2015-01-24T21:21:27-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/579012-use-prettytable-and-xtopdf-to-create-pdf-tables-wi/
<p style="color: grey">
Python
recipe 579012
by <a href="/recipes/users/4173351/">Vasudev Ram</a>
(<a href="/recipes/tags/data/">data</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/prettytable/">prettytable</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/tabular/">tabular</a>, <a href="/recipes/tags/xtopdf/">xtopdf</a>).
</p>
<p>This recipe shows how to create tabular data in PDF format, supporting neat borders, and alignment and padding of columns, using the Python libraries called PrettyTable and xtopdf.</p>
Random Password Generation (Python)
2014-08-10T15:50:40-07:00Paul Wolfhttp://code.activestate.com/recipes/users/4190553/http://code.activestate.com/recipes/578920-random-password-generation/
<p style="color: grey">
Python
recipe 578920
by <a href="/recipes/users/4190553/">Paul Wolf</a>
(<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/password/">password</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/random/">random</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/strong/">strong</a>).
</p>
<p>Generate a password (or other secure token) using a pattern language similar to regular expressions. We'll use the <code>strgen</code> module that enables a user to generate test data, unique ids, passwords, vouchers or other randomized data very quickly using a template language. The template language is superficially similar to regular expressions but instead of defining how to match or capture strings, it defines how to generate randomized strings.</p>
String to Binary (Python)
2014-07-30T07:20:22-07:00p@ntut$http://code.activestate.com/recipes/users/4183895/http://code.activestate.com/recipes/578291-string-to-binary/
<p style="color: grey">
Python
recipe 578291
by <a href="/recipes/users/4183895/">p@ntut$</a>
(<a href="/recipes/tags/binary/">binary</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/to/">to</a>).
Revision 2.
</p>
<p>String to binary snippet, python3+</p>
Decimal Number To Byte(s) And String To Byte(s) Converter. (Python)
2012-01-24T21:11:47-08:00Barry Walkerhttp://code.activestate.com/recipes/users/4177147/http://code.activestate.com/recipes/578025-decimal-number-to-bytes-and-string-to-bytes-conver/
<p style="color: grey">
Python
recipe 578025
by <a href="/recipes/users/4177147/">Barry Walker</a>
(<a href="/recipes/tags/bytes/">bytes</a>, <a href="/recipes/tags/converter/">converter</a>, <a href="/recipes/tags/decimal/">decimal</a>, <a href="/recipes/tags/linux/">linux</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/windows/">windows</a>).
</p>
<p>A function to convert decimal integer numbers, (from 0 to 255), into byte(s) format.
Another function calling the above function to convert ASCII strings into byte(s) format.</p>
<p>Python 3.1.3 (r313:86834, Nov 28 2010, 10:01:07)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.</p>
<pre class="prettyprint"><code>>>> exec(open('/home/G0LCU/Desktop/Code/d2b.py').read())
>>> a=78
>>> type(a)
<class 'int'>
>>> b=d2b(a)
>>> print(b)
b'N'
>>> type(b)
<class 'bytes'>
>>> text="\x00(C)2012, B.Walker, G0LCU.\xFF"
>>> len(text)
27
>>> type(text)
<class 'str'>
>>> newtext=t2b(text)
>>> len(newtext)
27
>>> print(newtext)
b'\x00(C)2012, B.Walker, G0LCU.\xff'
>>> type(newtext)
<class 'bytes'>
</code></pre>
<p>It requires NOTHING special at all to work and can be run like above or imported from
the correct "Lib" drawer/folder/directorfy as:-</p>
<pre class="prettyprint"><code>>>> import d2b
</code></pre>
<p>And when imported called as:-</p>
<pre class="prettyprint"><code>>>> d2b.d2b(some_number, optional_some_other_mumber)<RETURN/ENTER>
</code></pre>
<p>OR</p>
<pre class="prettyprint"><code>>>> d2b.t2b(some_ASCII_string)<RETURN/ENTER>
</code></pre>
<p>Read the code for much more information...</p>
<p>Issued under the GPL2 licence.</p>
<p>Enjoy finding simple solutions to often very difficult problems.</p>
<p>Bazza, G0LCU.</p>
lreplace() and rreplace(): Replace the beginning and ends of a strings (Python)
2010-06-04T02:18:48-07:00Dan McDougallhttp://code.activestate.com/recipes/users/4169722/http://code.activestate.com/recipes/577252-lreplace-and-rreplace-replace-the-beginning-and-en/
<p style="color: grey">
Python
recipe 577252
by <a href="/recipes/users/4169722/">Dan McDougall</a>
(<a href="/recipes/tags/regex/">regex</a>, <a href="/recipes/tags/replace/">replace</a>, <a href="/recipes/tags/string/">string</a>).
</p>
<p>Python newbies will often make the following mistake (I certainly have =):</p>
<pre class="prettyprint"><code>>>> test = """this is a test:
... tis the season for mistakes."""
>>> for line in test.split('\n'):
... print line.lstrip('this')
...
is a test
the season for mistakes.
</code></pre>
<p>The mistake is assuming that lstrip() (or rstrip()) strips a string (whole) when it actually strips all of the provided characters in the given string. Python actually comes with no function to strip a string from the left-hand or right-hand side of a string so I wrote this (very simple) recipe to solve that problem. Here's the usage:</p>
<pre class="prettyprint"><code>>>> test = """this is a test:
... tis the season for mistakes."""
>>> for line in test.split('\n'):
... print lreplace('this', '', line)
...
is a test
tis the season for mistakes.
</code></pre>
<p>I really wish Python had these functions built into the string object. I think it would be a useful addition to the standard library. It would also be nicer to type this:</p>
<pre class="prettyprint"><code>line.lreplace('this', '')
</code></pre>
<p>Instead of this:</p>
<pre class="prettyprint"><code>lreplace('this','',line)
</code></pre>
get all possible combinations of characters given a string (Python)
2011-08-15T04:15:42-07:00Yanghttp://code.activestate.com/recipes/users/4178968/http://code.activestate.com/recipes/577842-get-all-possible-combinations-of-characters-given-/
<p style="color: grey">
Python
recipe 577842
by <a href="/recipes/users/4178968/">Yang</a>
(<a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/permutation/">permutation</a>, <a href="/recipes/tags/string/">string</a>).
</p>
<p>This will give a result that is more than a permutation, but all possible combinations. An example is when input is 'abc', the output would be:
a,ab,abc,ac,acb,b,ba,bac,bc,bca,c,ca,cab,cb,cba</p>
Search sequences for sub-sequence (Python)
2011-08-19T05:17:00-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577850-search-sequences-for-sub-sequence/
<p style="color: grey">
Python
recipe 577850
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/find/">find</a>, <a href="/recipes/tags/searching/">searching</a>, <a href="/recipes/tags/sequence/">sequence</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/sublist/">sublist</a>, <a href="/recipes/tags/substring/">substring</a>).
</p>
<p>The list and tuple index() method and <code>in</code> operator test for element containment, unlike similar tests for strings, which checks for sub-strings:</p>
<pre class="prettyprint"><code>>>> "12" in "0123"
True
>>> [1, 2] in [0, 1, 2, 3]
False
</code></pre>
<p>These two functions, search and rsearch, act like str.find() except they operate on any arbitrary sequence such as lists:</p>
<pre class="prettyprint"><code>>>> search([1, "a", "b", 2, 3], ["b", 2])
2
</code></pre>
Split Strings w/ Multiple Separators (Python)
2011-03-20T20:33:13-07:00Kenneth Reitzhttp://code.activestate.com/recipes/users/4177394/http://code.activestate.com/recipes/577616-split-strings-w-multiple-separators/
<p style="color: grey">
Python
recipe 577616
by <a href="/recipes/users/4177394/">Kenneth Reitz</a>
(<a href="/recipes/tags/split/">split</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/string_parsing/">string_parsing</a>).
Revision 5.
</p>
<p>Splits strings with multiple separators instead of one (e.g. <code>str.split()</code>).</p>
"Comma float" to float (Python)
2010-02-11T22:19:41-08:00Matevz Leskohttp://code.activestate.com/recipes/users/4173032/http://code.activestate.com/recipes/577054-comma-float-to-float/
<p style="color: grey">
Python
recipe 577054
by <a href="/recipes/users/4173032/">Matevz Lesko</a>
(<a href="/recipes/tags/comma/">comma</a>, <a href="/recipes/tags/float/">float</a>, <a href="/recipes/tags/numbers/">numbers</a>, <a href="/recipes/tags/string/">string</a>).
Revision 2.
</p>
<p>Convert comma separated floating point number (12,3456) to float.</p>
converting numbers to their alphabetical style (Python)
2011-03-17T06:57:06-07:00amir naghavihttp://code.activestate.com/recipes/users/4177294/http://code.activestate.com/recipes/577607-converting-numbers-to-their-alphabetical-style/
<p style="color: grey">
Python
recipe 577607
by <a href="/recipes/users/4177294/">amir naghavi</a>
(<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/recursion/">recursion</a>, <a href="/recipes/tags/string/">string</a>).
Revision 4.
</p>
<p>converts numbers to alphabetical numbers </p>
Auto Named Decriptors (Python)
2010-10-19T22:55:16-07:00Aloys Baillethttp://code.activestate.com/recipes/users/4175355/http://code.activestate.com/recipes/577426-auto-named-decriptors/
<p style="color: grey">
Python
recipe 577426
by <a href="/recipes/users/4175355/">Aloys Baillet</a>
(<a href="/recipes/tags/automatically/">automatically</a>, <a href="/recipes/tags/constants/">constants</a>, <a href="/recipes/tags/descriptors/">descriptors</a>, <a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/name/">name</a>, <a href="/recipes/tags/string/">string</a>).
Revision 3.
</p>
<p>Using named Descriptors? Tired of duplicating the name of the instance in a string? A small metaclass can solve this.</p>
Split a string on capitalized / uppercase char using Python (Python)
2009-12-11T23:16:36-08:00activestatehttp://code.activestate.com/recipes/users/4172588/http://code.activestate.com/recipes/576984-split-a-string-on-capitalized-uppercase-char-using/
<p style="color: grey">
Python
recipe 576984
by <a href="/recipes/users/4172588/">activestate</a>
(<a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/string_parsing/">string_parsing</a>, <a href="/recipes/tags/text_processing/">text_processing</a>).
Revision 6.
</p>
<p>By user <a href="http://code.activestate.com/recipes/users/2629617/" rel="nofollow">http://code.activestate.com/recipes/users/2629617/</a> in comment on <a href="http://code.activestate.com/recipes/440698/" rel="nofollow">http://code.activestate.com/recipes/440698/</a> but modified slightly.</p>
<p>Splits any string on upper case characters.</p>
<p>Ex.</p>
<pre class="prettyprint"><code>>>> print split_uppercase("thisIsIt and SoIsThis")
this Is It and So Is This
</code></pre>
<p>note the two spaces after 'and'</p>
string Formatter that renders None values as empty strings (Python)
2010-05-14T18:35:27-07:00Antonio Cunihttp://code.activestate.com/recipes/users/4169762/http://code.activestate.com/recipes/577227-string-formatter-that-renders-none-values-as-empty/
<p style="color: grey">
Python
recipe 577227
by <a href="/recipes/users/4169762/">Antonio Cuni</a>
(<a href="/recipes/tags/formatting/">formatting</a>, <a href="/recipes/tags/none/">none</a>, <a href="/recipes/tags/string/">string</a>).
</p>
<p>This string Formatter works exactly as the default string.Formatter one (i.e., as str.format), with the exception that None values are rendered as empty strings instead of "None". Moreover, any attempt to access attributes or items of None values is rendered as an empty string as well, instead of raising an exception. <br />
E.g. fmt.format('{a}{a.foo}{a[0]}', a=None) == ''</p>
<p>This is useful e.g. when filling a template with values that are fetched from a DB, where usually None means empty.</p>
Approximately Equal (Python)
2010-03-17T17:05:51-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577124-approximately-equal/
<p style="color: grey">
Python
recipe 577124
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/comparisons/">comparisons</a>, <a href="/recipes/tags/distance/">distance</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/maths/">maths</a>, <a href="/recipes/tags/numeric/">numeric</a>, <a href="/recipes/tags/string/">string</a>).
</p>
<p>Generic "approximately equal" function for any object type, with customisable error tolerance.</p>
<p>When called with float arguments, approx_equal(x, y[, tol[, rel]) compares x and y numerically, and returns True if y is within either absolute error tol or relative error rel of x, otherwise return False. The function defaults to sensible default values for tol and rel.</p>
<p>For any other pair of objects, approx_equal() looks for a method __approx_equal__ and, if found, calls it with arbitrary optional arguments. This allows types to define their own concept of "close enough".</p>
Scramble a string of words, preserving spaces (Python)
2010-06-25T20:44:04-07:00Kai Malleahttp://code.activestate.com/recipes/users/4174276/http://code.activestate.com/recipes/577275-scramble-a-string-of-words-preserving-spaces/
<p style="color: grey">
Python
recipe 577275
by <a href="/recipes/users/4174276/">Kai Mallea</a>
(<a href="/recipes/tags/scramble/">scramble</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/words/">words</a>).
</p>
<p>The following function will scramble a string, preserving spaces that separate the words, and return the result. I used this for a word game that scrambled words and phrases, which a player then attempted to descramble. For example, scrambling the following string: "teenage mutant ninja turtles" would return "etegnae tamtnu jnnai urtltes"</p>
partitionall() - partition until the end (Python)
2010-03-01T15:27:07-08:00Shashwat Anandhttp://code.activestate.com/recipes/users/4172995/http://code.activestate.com/recipes/577060-partitionall-partition-until-the-end/
<p style="color: grey">
Python
recipe 577060
by <a href="/recipes/users/4172995/">Shashwat Anand</a>
(<a href="/recipes/tags/string/">string</a>).
Revision 4.
</p>
<p>Search for the separator sep in string s, and return the part before it, the separator itself, and the part after it continuously untill all the seperator finishes. If the separator is not found, return string s. It works like split() combined with partition()</p>
string multi-partitioning (Python)
2010-03-26T20:03:59-07:00Michael Grünewaldhttp://code.activestate.com/recipes/users/4172244/http://code.activestate.com/recipes/577017-string-multi-partitioning/
<p style="color: grey">
Python
recipe 577017
by <a href="/recipes/users/4172244/">Michael Grünewald</a>
(<a href="/recipes/tags/partition/">partition</a>, <a href="/recipes/tags/string/">string</a>).
Revision 6.
</p>
<p>Works like the <code>partition</code> method of strings in Python2.5+, but has support for more than one delimiter.</p>
<p><em>Better description by Gabriel Genellina:</em></p>
<blockquote>
<p>Split the string at separator boundaries. The separators are searched from left to right, in the same order specified, and one after another. Unlike <code>partition</code>, all of them must be present (else <code>ValueError</code> is raised). Only one split per separator occurrence is done. Returns a list containing one more element than separators were given: first, text from beginning of the string up to (but not including) the first separator; the first separator itself; text between the first separator and the second one; the second separator; and so on. The last element contains all text following the last separator.</p>
</blockquote>
Simple reverse converter of unicode code points string (Python)
2009-09-22T20:02:32-07:00Ryanhttp://code.activestate.com/recipes/users/4171767/http://code.activestate.com/recipes/576909-simple-reverse-converter-of-unicode-code-points-st/
<p style="color: grey">
Python
recipe 576909
by <a href="/recipes/users/4171767/">Ryan</a>
(<a href="/recipes/tags/code/">code</a>, <a href="/recipes/tags/points/">points</a>, <a href="/recipes/tags/prefix/">prefix</a>, <a href="/recipes/tags/reverse/">reverse</a>, <a href="/recipes/tags/str/">str</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/u/">u</a>, <a href="/recipes/tags/unicode/">unicode</a>).
Revision 4.
</p>
<p>It's a simple recipe to convert a str type string with pure unicode code point (e.g string = <strong>"\u5982\u679c\u7231"</strong> ) to an unicode type string.
Actually, this method has the same effect with <strong>'u'</strong> prefix. But differently, it allows you to pass a variable of code points string as well as a constant one.</p>
Convert datetime in python to user friendly representation. (Python)
2009-08-15T01:00:03-07:00Jai Vikram Singh Vermahttp://code.activestate.com/recipes/users/4171450/http://code.activestate.com/recipes/576880-convert-datetime-in-python-to-user-friendly-repres/
<p style="color: grey">
Python
recipe 576880
by <a href="/recipes/users/4171450/">Jai Vikram Singh Verma</a>
(<a href="/recipes/tags/ago/">ago</a>, <a href="/recipes/tags/datetime/">datetime</a>, <a href="/recipes/tags/parse/">parse</a>, <a href="/recipes/tags/representation/">representation</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/user_friendly/">user_friendly</a>).
</p>
<p>A small contribution to the developer community.</p>
<p>This module caters to the need of developers who want to put date & time of post in terms like <br />
"X days, Y hrs ago", "A hours B mins ago", etc. in their applications rather then a basic timestamp <br />
like "2009-08-15 03:03:00". Additionally it also <br />
provides since epoch for a given datetime. </p>
<p>It takes in a Python datetime object as an input <br />
and provides a fancy datetime (as I call it) and <br />
the seconds since epoch. </p>