Python split ошибка

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

If you pass an empty string to the str.split() method, you will raise the ValueError: empty separator. If you want to split a string into characters you can use list comprehension or typecast the string to a list using list().

def split_str(word):
    return [ch for ch in word]

my_str = 'Python'

result = split_str(my_str)
print(result)

This tutorial will go through the error in detail with code examples.


Table of contents

  • Python ValueError: empty separator
  • Example #1: Split String into Characters
    • Solution #1: Use list comprehension
    • Solution #2: Convert string to a list
  • Example #2: Split String using a Separator
    • Solution
  • Summary

Python ValueError: empty separator

In Python, a value is information stored within a particular object. We will encounter a ValueError in Python when we use an operation or function that receives an argument with the right type but an inappropriate value.

The split() method splits a string into a list. We can specify the separator, and the default is whitespace if we do not pass a value for the separator. In this example, an empty separator "" is an inappropriate value for the str.split() method.

Example #1: Split String into Characters

Let’s look at an example of trying to split a string into a list of its characters using the split() method.

my_str = 'research'

chars = my_str.split("")

print(chars)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [7], in <cell line: 3>()
      1 my_str = 'research'
----> 3 chars = my_str.split("")
      5 print(chars)

ValueError: empty separator

The error occurs because did not pass a separator to the split() method.

Solution #1: Use list comprehension

We can split a string into a list of characters using list comprehension. Let’s look at the revised code:

my_str = 'research'

chars = [ch for ch in my_str]

print(chars)

Let’s run the code to get the list of characters:

['r', 'e', 's', 'e', 'a', 'r', 'c', 'h']

Solution #2: Convert string to a list

We can also convert a string to a list of characters using the built-in list() method. Let’s look at the revised code:

my_str = 'research'

chars = list(my_str)

print(chars)

Let’s run the code to get the result:

['r', 'e', 's', 'e', 'a', 'r', 'c', 'h']

Example #2: Split String using a Separator

Let’s look at another example of splitting a string.

my_str = 'research is fun'

list_of_str = my_str.split("")

print(list_of_str)

In the above example, we want to split the string by the white space between each word. Let’s run the code to see what happens:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [10], in <cell line: 3>()
      1 my_str = 'research.is.fun'
----> 3 list_of_str = my_str.split("")
      5 print(list_of_str)

ValueError: empty separator

The error occurs because "" is an empty separator and does not represent white space.

Solution

We can solve the error by using the default value of the separator, which is white space. We need to call the split() method without specifying an argument to use the default separator. Let’s look at the revised code:

my_str = 'research is fun'

list_of_str = my_str.split()

print(list_of_str)

Let’s run the code to see the result:

['research', 'is', 'fun']

Summary

Congratulations on reading to the end of this tutorial!

For further reading on Python ValueErrors, go to the articles:

  • How to Solve Python ValueError: year is out of range
  • How to Solve Python ValueError: dictionary update sequence element #0 has length N; 2 is required

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Здравствуйте, из-за чего может не работать метод split?
>>> str = ‘hello’
>>> print(str.split())
[‘hello’]
>>> print(str.split( ))
[‘hello’]
>>> print(str.split(‘i’, 1))
[‘hello’]
>>>


  • Вопрос задан

    более трёх лет назад

  • 1265 просмотров

Укажи символ по которому хочешь разделить строку.

str = 'Python'
print (str.split('t'))

>>> [‘Py’, ‘hon’]

Пригласить эксперта


  • Показать ещё
    Загружается…

04 июн. 2023, в 12:23

30000 руб./за проект

04 июн. 2023, в 12:18

20000 руб./за проект

04 июн. 2023, в 12:07

2000 руб./за проект

Минуточку внимания

There are instances in which you might need to divide Python lists into smaller chunks for simpler processing or just to focus your data analysis work on relevant data. A very prevalent case for this is when working with csv (Comma Separated Values) files.

In today’s short Python programming tutorial we will learn how to troubleshoot a very common mistake we do when beginning coding Python : we try to use the split() and splitlines() methods, which are basically string methods, on lists.

Fixing the ‘list’ object has no attribute ‘split’ error

Let’s quickly create a list from a string – feel free to follow along by copying this code into your favorite development editor:

# define a Python string containing multiple elements
prog_lang = "Python,R,C#,Scala"
# create a list
prog_lang_lst = prog_lang.split(',')

We have used the split() method on our string to create our Python list:

print( prog_lang_lst)

This will return the following list:

['Python', 'R', 'C#', 'Scala']

Can’t divide Python lists using split

If we try to use the split() method to divide the list we get the error:

# this will result in an error
prog_lang_lst.split(',')

Here’s the exception that will be thrown:

AttributeError: 'list' object has no attribute 'split'

Ways to fix our split AttributeError

We can easily split our lists in a few simple ways, feel free to use whicever works for you.

Print our list elements

Our list is an iterable, so we can easily loop into it and print its elements as strings:

for e in prog_lang_lst:
    print (e)

The result will be:

Python
R
C#
Scala

Split list into multiple lists

We loop through the list and divide its elements according to the separating character – a comma in our case:

for e in prog_lang_lst:
    print (e.split(','))

Here’s the output:

['Python']
['R']
['C#']
['Scala']

Split and join the list elements to a string

We can easily use the join method to join the list elements into a string

print(', '.join(prog_lang_lst))

This will render the following result:

Python, R, C#, Scala

Split into a list of lists

We can use a list comprehension to split our list into a list of lists as shown below:

prog_lang_l_lst = [e.split(',') for e in prog_lang_lst]
print(prog_lang_l_lst)

Here’s the output

[['Python'], ['R'], ['C#'], ['Scala']]

Posted on Jan 03, 2023


Python shows AttributeError: ’list’ object has no attribute ‘split’ when you try to use the split() method on a list object instead of a string.

To fix this error, you need to make sure you are calling the split() method on a string object and not a list. Read this article to learn more.

The split() method is a string method that is used to divide a string into a list of substrings based on a specified delimiter.

When you call this method on a list object as shown below:

words = ['hello', 'world']
words.split()

You’ll receive the following error response from Python:

To resolve this error, you need to make sure you are calling the split() method on a string.

You can use an if statement to check if your variable contains a string type value like this:

words = "hello world"

if type(words) is str:
    new_list = words.split()
    print(new_list)
else:
    print("Variable is not a string")

In the example above, the type() function is called to check on the type of the words variable.

When it’s a string, then the split() method is called and the new_list variable is printed. Otherwise, print “Variable is not a string” as the output.

If you have a list of string values that you want to split into a new list, you have two options:

  1. Access the list element at a specific index using square brackets [] notation
  2. Use a for loop to iterate over the values of your list

Let’s see how both options above can be done.

Access a list element with [] notation

Suppose you have a list of names and numbers as shown below:

users = ["Nathan:92", "Jane:42", "Leo:29"]

Suppose you want to split the values of the users list above as their own list.

One way to do it is to access the individual string values and split them like this:

users = ["Nathan:92", "Jane:42", "Leo:29"]

new_list = users[0].split(":")

print(new_list)  # ['Nathan', '92']

As you can see, calling the split() method on a string element contained in a list works fine.

Note that the split() method has an optional parameter called delimiter, which specifies the character or string that is used to split the string.

By default, the delimiter is any whitespace character (such as a space, tab, or newline).

The code above uses the colon : as the delimiter, so you need to pass it as an argument to split()

Using a for loop to iterate over a list and split the elements

Next, you can use a for loop to iterate over the list and split each value.

You can print the result as follows:

users = ["Nathan:92", "Jane:42", "Leo:29"]

for user in users:
    result = user.split(":")
    print(result)

The code above produces the following output:

['Nathan', '92']
['Jane', '42']
['Leo', '29']

Printing the content of a file with split()

Finally, this error commonly occurs when you try to print the content of a file you opened in Python.

Suppose you have a users.txt file with the following content:

EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL
198,Donald,OConnell,doconnel@mail.com
199,Douglas,Grant,dgrant@mail.com
200,Jennifer,Whalen,jwhalen@mail.com
201,Michael,Hartl,mhartl@mail.com

Next, you try to read each line of the file using the open() and readlines() functions like this:

readfile = open("users.txt", "r")
readlines = readfile.readlines()

result = readlines.split(",")

The readlines() method returns a list containing each line in the file as a string.

When you try to split a list, Python responds with the AttributeError message:

Traceback (most recent call last):
  File "script.py", line 10, in <module>
    result = readlines.split(",")
             ^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'split'

To resolve this error, you need to call split() on each line in the readlines object.

Use the for loop to help you as shown below:

readfile = open("users.txt", "r")
readlines = readfile.readlines()

for line in readlines:
    result = line.split(',')
    print(result)

The output of the code above will be:

['EMPLOYEE_ID', 'FIRST_NAME', 'LAST_NAME', 'EMAILn']
['198', 'Donald', 'OConnell', 'doconnel@mail.comn']
['199', 'Douglas', 'Grant', 'dgrant@mail.comn']
['200', 'Jennifer', 'Whalen', 'jwhalen@mail.comn']
['201', 'Michael', 'Hartl', 'mhartl@mail.com']

You can manipulate the file content using Python as needed.

For example, you can print only the FIRST_NAME detail from the file using print(result[1]):

for line in readlines:
    result = line.split(',')
    print(result[1])

Output:

FIRST_NAME
Donald
Douglas
Jennifer
Michael

Conclusion

To conclude, the Python “AttributeError: ’list’ object has no attribute ‘split’” occurs when you try to call the split() method on a list.

The split() method is available only for strings, so you need to make sure you are actually calling the method on a string.

When you need to split elements inside a list, you can use the for loop to iterate over the list and call the split() method on the string values inside it.

Понравилась статья? Поделить с друзьями:
  • Python requests обработка ошибок
  • Python requests коды ошибок
  • Python pyqt5 сообщение об ошибке
  • Python postgresql обработка ошибок
  • Python manage py createsuperuser ошибка