2
votes
a = string.split("Test Test2 Test3"," ")

This returns an error:

Message File Name   Line    Position    
Traceback               
    <module>    C:\pyWiz.py 43      
AttributeError: 'module' object has no attribute 'split'                

Yes, I imported the string module. Why is this happening?

5
What version of Python are you using? - dfb
Works for me with Python 2.7. But you can also use string methods. - Keith

5 Answers

8
votes

Use:

a = 'Test Test2 Test3'.split(' ')

(i.e. split method of str type). string.split is deprecated in 2.x and gone in 3.x.

3
votes

string is a module while you were looking for the class/type object str. I would recommend doing this though:

a = "Test Test2 Test3".split()
1
votes

why not just "Test Test2 Test3".split() ?

0
votes
a = "Test Test2 Test3".split(" ")
0
votes
>>> a = 'jetpack ferret pizza lawyer'.split()
>>> a
['jetpack', 'ferret', 'pizza', 'lawyer']

>>> b = 'jetpack ferret pizza lawyer'
>>> b.split()
['jetpack', 'ferret', 'pizza', 'lawyer']
>>> b
'jetpack ferret pizza lawyer'

>>> c = """very   
looooooooooooooooooooooong string      with trailing random whitespace    """
>>> c = c.split()
>>> c
['very', 'looooooooooooooooooooooong', 'string', 'with', 'trailing', 'random', 'whitespace']

>>> d = 'dog;_cat;_fish;_'.split(';_')
>>> d
['dog', 'cat', 'fish', '']

It is to note that most times you don't need to specify the separator (which can be made of mutiple characters).

If we simplify, giving no arguments to the split function gets you rid of all whitespace (i.e. spaces, tabs, newlines, returns), and this is a preferred behavior to work with input from a file, a shell etc, and also notably in a most common use of this idiom: hard coding a list of strings saving some annoying typing of commas and quotes.

Also be aware you're gonna get empty strings in your list if:

  • input string ends or starts with one or more characters you defined as separator (see my last example)

  • there's more than one separator between group of characters you want to get