Most viewed recipes tagged "string"http://code.activestate.com/recipes/tags/string/views/2015-01-24T21:21:27-08:00ActiveState Code RecipesSplit 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> 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>&gt;&gt;&gt; test = """this is a test: ... tis the season for mistakes.""" &gt;&gt;&gt; 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>&gt;&gt;&gt; test = """this is a test: ... tis the season for mistakes.""" &gt;&gt;&gt; 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> 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>&gt;&gt;&gt; exec(open('/home/G0LCU/Desktop/Code/d2b.py').read()) &gt;&gt;&gt; a=78 &gt;&gt;&gt; type(a) &lt;class 'int'&gt; &gt;&gt;&gt; b=d2b(a) &gt;&gt;&gt; print(b) b'N' &gt;&gt;&gt; type(b) &lt;class 'bytes'&gt; &gt;&gt;&gt; text="\x00(C)2012, B.Walker, G0LCU.\xFF" &gt;&gt;&gt; len(text) 27 &gt;&gt;&gt; type(text) &lt;class 'str'&gt; &gt;&gt;&gt; newtext=t2b(text) &gt;&gt;&gt; len(newtext) 27 &gt;&gt;&gt; print(newtext) b'\x00(C)2012, B.Walker, G0LCU.\xff' &gt;&gt;&gt; type(newtext) &lt;class 'bytes'&gt; </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>&gt;&gt;&gt; import d2b </code></pre> <p>And when imported called as:-</p> <pre class="prettyprint"><code>&gt;&gt;&gt; d2b.d2b(some_number, optional_some_other_mumber)&lt;RETURN/ENTER&gt; </code></pre> <p>OR</p> <pre class="prettyprint"><code>&gt;&gt;&gt; d2b.t2b(some_ASCII_string)&lt;RETURN/ENTER&gt; </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> Bytes-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> 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> Implementation of Knuth–Morris–Pratt algorithm (C) 2011-10-15T00:33:41-07:00Shao-chuan Wanghttp://code.activestate.com/recipes/users/4168519/http://code.activestate.com/recipes/577908-implementation-of-knuthmorrispratt-algorithm/ <p style="color: grey"> C recipe 577908 by <a href="/recipes/users/4168519/">Shao-chuan Wang</a> (<a href="/recipes/tags/kmp/">kmp</a>, <a href="/recipes/tags/matching/">matching</a>, <a href="/recipes/tags/string/">string</a>). Revision 2. </p> <p>Knuth–Morris–Pratt (KMP) is a linear time string matching algorithm.</p> <p><a href="http://en.wikipedia.org/wiki/Knuth%25E2%2580%2593Morris%25E2%2580%2593Pratt_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm</a></p> <p>This recipe gives a C-version implementation.</p> Generate a salt (PHP) 2012-07-10T19:52:17-07:00Xavier L.http://code.activestate.com/recipes/users/4171602/http://code.activestate.com/recipes/576894-generate-a-salt/ <p style="color: grey"> PHP recipe 576894 by <a href="/recipes/users/4171602/">Xavier L.</a> (<a href="/recipes/tags/crypt/">crypt</a>, <a href="/recipes/tags/generation/">generation</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/hash/">hash</a>, <a href="/recipes/tags/pass/">pass</a>, <a href="/recipes/tags/password/">password</a>, <a href="/recipes/tags/salt/">salt</a>, <a href="/recipes/tags/secure/">secure</a>, <a href="/recipes/tags/security/">security</a>, <a href="/recipes/tags/string/">string</a>). Revision 6. </p> <p>This function will generate a salt for use with passwords ranging using characters in range a to z, A to Z, 0 to 9 and !@#$%&amp;<em>?. The characters are sorted in a random value and can appear more than one time in the string. This way, this function is more powerful than the *shuffle()</em> function. This means that the salt could also be longer than the character list.</p> Converty decimal/integer number to binary string in Python (Python) 2009-07-17T09:17:32-07:00Vishal Saprehttp://code.activestate.com/recipes/users/4166412/http://code.activestate.com/recipes/576847-converty-decimalinteger-number-to-binary-string-in/ <p style="color: grey"> Python recipe 576847 by <a href="/recipes/users/4166412/">Vishal Sapre</a> (<a href="/recipes/tags/binary/">binary</a>, <a href="/recipes/tags/decimal/">decimal</a>, <a href="/recipes/tags/integer/">integer</a>, <a href="/recipes/tags/string/">string</a>). </p> <p>This is a very simple look-up based method for converting integer to binary string. In my tests, using 'timeit', its the fastest around. And with increasing value of input decimal number, it surpases any 'run time computation' based method doing the above.</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>&gt;&gt;&gt; print split_uppercase("thisIsIt and SoIsThis") this Is It and So Is This </code></pre> <p>note the two spaces after 'and'</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 &amp; 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> 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> C# String.Replace with a char array (Java) 2010-12-24T09:58:35-08:00John Hurlimanhttp://code.activestate.com/recipes/users/4174599/http://code.activestate.com/recipes/577516-c-stringreplace-with-a-char-array/ <p style="color: grey"> Java recipe 577516 by <a href="/recipes/users/4174599/">John Hurliman</a> (<a href="/recipes/tags/csharp/">csharp</a>, <a href="/recipes/tags/replace/">replace</a>, <a href="/recipes/tags/string/">string</a>). </p> <p>Takes a string and replaces all characters matching a given array with a given string</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>&gt;&gt;&gt; "12" in "0123" True &gt;&gt;&gt; [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>&gt;&gt;&gt; search([1, "a", "b", 2, 3], ["b", 2]) 2 </code></pre> 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> 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> 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> Sort strings containing german umlauts in correct order (Python) 2008-09-13T14:28:54-07:00Andreas Maierhttp://code.activestate.com/recipes/users/4167085/http://code.activestate.com/recipes/576507-sort-strings-containing-german-umlauts-in-correct-/ <p style="color: grey"> Python recipe 576507 by <a href="/recipes/users/4167085/">Andreas Maier</a> (<a href="/recipes/tags/din5007/">din5007</a>, <a href="/recipes/tags/sort/">sort</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/umlaut/">umlaut</a>). Revision 13. </p> <p>A function which implements sort keys for the german language according to DIN 5007.</p> 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>