Using Python 2.7.3.1
I don't understand what the problem is with my coding! I get this error: AttributeError: 'list' object has no attribute 'split
This is my code:
myList = ['hello']
myList.split()
The Python "AttributeError: 'list' object has no attribute 'split'" occurs when we call the split() method on a list instead of a string. To solve the error, call split() on a string, e.g. by accessing the list at a specific index or by iterating over the list.
In Python, the list data structure stores elements in sequential order. To convert a string to a list object, we can use the split() function on the string, giving us a list of strings. However, we cannot apply the split() function to a list.
If you are getting an object that has no attribute error then the reason behind it is because your indentation is goofed, and you've mixed tabs and spaces.
To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.
You can simply do list(myList[0])
as below:
>>> myList = ['hello']
>>> myList=list(myList[0])
>>> myList
['h', 'e', 'l', 'l', 'o']
See documentation here
To achieve what you are looking for:
myList = ['hello']
result = [c for c in myList[0]] # a list comprehension
>>> print result
['h', 'e', 'l', 'l', 'o']
More info on list comprehensions: http://www.secnetix.de/olli/Python/list_comprehensions.hawk
Lists in python do not have a split method. split is a method of strings(str.split()
)
Example:
>>> s = "Hello, please split me"
>>> print s.split()
['Hello,', 'please', 'split', 'me']
By default, split splits on whitespace.
Check out more info: http://www.tutorialspoint.com/python/string_split.htm:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With