2
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?

2
  • What version of Python are you using? Commented Feb 10, 2011 at 23:59
  • Works for me with Python 2.7. But you can also use string methods. Commented Feb 11, 2011 at 0:00

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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()

Comments

1

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

2 Comments

I suppose that works, but it's just not what I'm used to. It worked fine in 2.x
@Patrick Moriarty: It used to be all right, but in current Python you wont need to import string anymore.
0
a = "Test Test2 Test3".split(" ")

Comments

0
>>> 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.