perl's split function in Python?

metallicafan

[H]ard|DCer of the Month - May 2010
2FA
Joined
Mar 30, 2005
Messages
2,205
If remember correctly perl has a function called split that will take a string and break it up in to several strings and put them into an array. Is there any built in function like this in python?
 
Yes, it's called split().

python.org said:
split( [sep [,maxsplit]])
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made). Consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, "'1,,2'.split(',')"returns "['1', '', '2']"). The sep argument may consist of multiple characters (for example, "'1, 2, 3'.split(', ')" returns "['1', '2', '3']"). Splitting an empty string with a specified separator returns "['']".

If sep is not specified or is None, a different splitting algorithm is applied. First, whitespace characters (spaces, tabs, newlines, returns, and formfeeds) are stripped from both ends. Then, words are separated by arbitrary length strings of whitespace characters. Consecutive whitespace delimiters are treated as a single delimiter ("'1 2 3'.split()" returns "['1', '2', '3']"). Splitting an empty string or a string consisting of just whitespace returns an empty list.
 
:D :D hey thanks a lot I now feel foolish, but i couldnt find that in my book. Looks like I might be using python.org more often.

thanks again
 
I am very new to python but when I use split() i am getting an error. I am trying to open a file for input and then grab a line and split it up by spaces and put each item in a HTML table.

Code:
infile = open( 'memwarehouse.dat', 'r' )

  print "<table>"
  print "<tr>"
  print "<th>Part Number</th>"
  print "<th>Part Description</th>"
  print "<th>Numberin Stock</th>"
  print "<th>Price per Item</th>"
  print "</tr>"

  for line in infile:
     data = split( " ", line )
     print "<tr>"
     for g in data:
        print "<td>" + g + "</td>"
     print "</td>"

This code might help give you a better idea what I'm doing. However, when I try to run the program i get an error saying: "NameError: global name 'split' is not defined"

I did some reading and discovered that I needed the re module so i added that but still no luck. When reading I came accross a compile() function. If someone could just give me a general example of using the split() function that would be great, I'm not even asking people to fix my code. Thanks in advance.
 
Try data = line.split() instead.
(Split() is a method of string objects. Very OO.)
 
HHunt said:
Try data = line.split() instead.
(Split() is a method of string objects. Very OO.)

bingo. That worked. Now can you help me to understand why? How does the split() function that I tried to use work? If i wanted to split on a '/' would i use line.split( '/' )? thank you HHunt.
 
I don't know how familiar with OO programming you are, so I'll do the basics:

A Class is a set of properties and methods. When you create one, you have an object, which is an instance of that class.
(The class is the description that you make object from, so to speak. There is one str class, but each str object is different.)

In python, everything is an object. When you make a string, you actually make an instance of the str class. That class contains not only the actual string, but also a number of methods (like split) that you can use. When you use somestring.split(), you ask the str to split itself, by using one of the methods in the str class. What you tried to do is more like asking the interpreter to split it for you. Except for a few builtin functions, it's not how python works.
(A somewhat related approach that you will meet is asking another object to do things for you. In this case that would look something like StringSplitter.splitStr(myString, "/"), if a StringSplitter object existed and could do that.)

Some of these things are more explicit in stricter languages (e.g. java), because you have to declare each variable as a type (often, but not always, a class) before you can use it, and then you know the capabilities of that type.
In python, the type of a piece of data is decided when it's created. If you split a string, the results will be strings, and if you say var = 1, it is an integer.
(It's as strict as java, it just removes the need to declare things.)

If you have the commandline python program (you most likely do), you can try using the builtin functions type() and dir() on anything to see what it is and can do.
(Since they are builtin, you do actually use them as type(something) .)
E.g. :
Code:
>>> a,b = "1", 2
>>> a, b
('1', 2)
>>> type(a), type(b)
(<type 'str'>, <type 'int'>)
>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
>>> int(a) + b
3
>>> a + str(b)
'12'
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Notice how 'split' is in that list.
 
HHunt - thank you very much. I am somewhat familiar with OO programming. Your explanation help clear things up somewhat. I am just new to Python and the syntax takes some getting used to when I am used to C++. Thanks again.
 
metallicafan said:
HHunt - thank you very much. I am somewhat familiar with OO programming. Your explanation help clear things up somewhat. I am just new to Python and the syntax takes some getting used to when I am used to C++. Thanks again.

Ah, right. At least I didn't underexplain it. :D
 
HHunt said:
Ah, right. At least I didn't underexplain it. :D

:D :D better to be safe that sorry huh? no just the right amount of explaination accually! thanks
 
you could also use the string module
Code:
import string

l = string.split('foo,bar,baz',',')
if you don't want to use the string's method.
 
Back
Top