|
Python - two different splits
In Python, there are two different split methods you can use to break up a string into a number of substrings, based on a particular separator. If you know exactly what character(s) your separator will be - e.g. exactly one space - the you can use the method in the string class. By if your separator is less well defined - e.g. if it's one or more space characters - then you'll want to use the split within the re class.
import re
space = re.compile(r'\s+')
data ="Perl Python PHP Prolog Pascal"
langs = data.split(" ")
print langs
langs = space.split(data)
print langs
How does that run?
['Perl', 'Python', '', '', 'PHP', 'Prolog\tPascal']
['Perl', 'Python', 'PHP', 'Prolog', 'Pascal']
The first split looks fairly poor - we've split at single space characters BUT the input string had multiple spaces in one place, and a tab in another
The second split - on a regular expression "one or more white space characters" worked much better, and is typically what you might use for data that was user entered or user edited. (written 2007-03-15 17:53:57)
Associated topics are indexed under Y108 - Python - String Handling
Some other Articles
PHP Image upload scriptFile and URL reading in PHPBank Holiday country breaks in Melksham, WiltshireTraining in LuaPython - two different splitsFalse imprisonment - a contrast from the newsExpress serviceWeekend VisitorsSpring PicturesA week is a long time in the life of a conference centre
|
2259 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|