Меню

Empty separator python ошибка

TLDR:
If you don’t specify a character for str.split to split by, it defaults to a space or tab character. My error was due to the fact that I did not have a space between my quotes.


In case you were wondering, the separator I specified is a space:

words = stuff.split(" ")

The string in question is This is an example of a question.
I also tried # as the separator and put #‘s into my sentence and got the same error.

Edit: Here is the complete block

def break_words(stuff):
"""This function will break up words for us."""
    words = stuff.split(" ")
    return words
sentence = "This is an example of a sentence."
print break_words(sentence)

When I run this as py file, it works.
but when I run the interpreter, import the module, and type:
sentence = "This is an example of a sentence."
followed by print break_words(sentence)

I get the above mentioned error.

And yes, I realise that this is redundant, I’m just playing with functions.

Edit 2: Here is the entire traceback:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ex25.py", line 6, in break_words
words = stuff.split(' ')

Edit 3: Well, I don’t know what I did differently, but when I tried it again now, it worked:

>>> s = "sdfd dfdf ffff"
>>> ex25.break_words(s)
['sdfd', 'dfdf', 'ffff']
>>> words = ex25.break_words(s)
>>>

As you can see, no errors.

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!

Summary: You can split a string using an empty separator using –
(i) list constructor
(ii) map+lambda
(iii) regex
(iv) list comprehension

Minimal Example:

text = '12345'

# Using list()
print(list(text))

# Using map+lambda
print(list(map(lambda c: c, text)))

# Using list comprehension
print([x for x in text])

# Using regex
import re
# Approach 1
print([x for x in re.split('', text) if x != ''])
# Approach 2
print(re.findall('.', text))

Problem Formulation

📜Problem: How to split a string using an empty string as a separator?

Example: Consider the following snippet –

a = 'abcd'
print(a.split(''))

Output:

Traceback (most recent call last):
  File "C:UsersSHUBHAM SAYONPycharmProjectsFinxterBlogsFinxter.py", line 2, in <module>
    a.split('')
ValueError: empty separator

Expected Output:

['a', 'b', 'c', 'd']

So, this essentially means that when you try to split a string by using an empty string as the separator, you will get a ValueError. Thus, your task is to find out how to eliminate this error and split the string in a way such that each character of the string is separately stored as an item in a list.


Now that we have a clear picture of the problem let us dive into the solutions to solve the problem.

Method 1: Use list()

Approach: Use the list() constructor and pass the given string as an argument within it as the input, which will split the string into separate characters.

Note: list() creates a new list object that contains items obtained by iterating over the input iterable. Since a string is an iterable formed by combining a group of characters, hence, iterating over it using the list constructor yields a single character at each iteration which represents individual items in the newly formed list.

Code:

a = 'abcd'
print(list(a))

# ['a', 'b', 'c', 'd']

🌎Related Read: Python list() — A Simple Guide with Video

Method 2: Use map() and lambda

Approach: Use the map() to execute a certain lambda function on the given string. All you need to do is to create a lambda function that simply returns the character passed to it as the input to the map object. That’s it! However, the map method will return a map object, so you must convert it to a list using the list() function.

Code:

a = 'abcd'
print(list(map(lambda c: c, a)))

# ['a', 'b', 'c', 'd']

Method 3: Use a list comprehension

Approach: Use a list comprehension that returns a new list containing each character of the given string as individual items.

Code:

a = 'abcd'
print([x for x in a])
# ['a', 'b', 'c', 'd']

🌎Related Read: List Comprehension in Python — A Helpful Illustrated Guide

Method 4: Using regex

The re.findall(pattern, string) method scans string from left to right, searching for all non-overlapping matches of the pattern. It returns a list of strings in the matching order when scanning the string from left to right.

🌎Related Read: Python re.findall() – Everything You Need to Know

Approach: Use the regular expression re.findall('.',a) that finds all characters in the given string ‘a‘ and stires them in a list as individual items.

Code:

import re
a = 'abcd'
print(re.findall('.',a))

# ['a', 'b', 'c', 'd']

Alternatively, you can also use the split method of the regex library in a list comprehension which returns each character of the string and eliminates empty strings.

Code:

import re
a = 'abcd'
print([x for x in re.split('',a) if x!=''])

# ['a', 'b', 'c', 'd']

🌎Related Read: Python Regex Split

Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

Conclusion

Hurrah! We have successfully solved the given problem using as many as four (five, to be honest) different ways. I hope this article helped you and answered your queries. Please subscribe and stay tuned for more interesting articles and solutions in the future.

Happy coding! 🙂


Regex Humor

Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee. (source)

shubham finxter profile image

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork
LinkedIn

Что такое хороший способ сделать some_string.split('') в python? Этот синтаксис дает ошибку:

a = '1111'
a.split('')

ValueError: empty separator

Я хотел бы получить:

['1', '1', '1', '1']

Ответ 1

Используйте list():

>>> list('1111')
['1', '1', '1', '1']

В качестве альтернативы вы можете использовать map():

>>> map(None, '1111')
['1', '1', '1', '1']

Разница во времени:

$ python -m timeit "list('1111')"
1000000 loops, best of 3: 0.483 usec per loop
$ python -m timeit "map(None, '1111')"
1000000 loops, best of 3: 0.431 usec per loop

Ответ 2

Можно напрямую записывать строки для

>>> list('1111')
['1', '1', '1', '1']

или использования списков

>>> [i for i in '1111']
['1', '1', '1', '1']

второй способ может быть полезен, если вы хотите разделить строки на подстроки длиной более 1 символа

>>> some_string = '12345'
>>> [some_string[i:i+2] for i in range(0, len(some_string), 2)]
['12', '34', '5']

Ответ 3

Строки являются итерабельными и могут быть проиндексированы, поэтому вам совсем не нужно разделить его:

>>> for char in '11111':
...   print char
... 
1
1
1
1
1
>>> '11111'[4]
'1'

Вы можете «разбить» его на вызов в список, но это не имеет большого значения:

>>> for char in list('11111'):
...   print char
... 
1
1
1
1
1
>>> list('11111')[4]
'1'

Поэтому вам нужно сделать это, только если ваш код явно ожидает список. Например:

>>> list('11111').append('2')
>>> l = list('11111')
>>> l.append(2)
>>> l
['1', '1', '1', '1', '1', 2]

Это не работает с прямой строкой:

>>> l.append('2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

В этом случае вам понадобится:

>>> l += '2'
>>> l
'111112'

Ответ 4

Метод # 1:

s="Amalraj"
l=[i for i in s]
print(l)

Вывод:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Способ №2:

s="Amalraj"
l=list(s)
print(l)

Вывод:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Способ № 3:

import re; # importing regular expression module
s="Amalraj"
l=re.findall('.',s)
print(l)

Вывод:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

TLDR : Если вы не указываете символ для str.split для разделения, по умолчанию используется пробел или символ табуляции. Моя ошибка была связана с тем, что между моими цитатами не было пробела.


В случае, если вам интересно, указанный мной разделитель является пробелом:

words = stuff.split(" ")

Строка в вопросе This is an example of a question. Я также попробовал # в качестве разделителя и вставил # в мое предложение, и получил ту же ошибку.

Изменить. Вот полный блок

def break_words(stuff):
"""This function will break up words for us."""
    words = stuff.split(" ")
    return words
sentence = "This is an example of a sentence."
print break_words(sentence)

Когда я запускаю это как py-файл, он работает. но когда я запускаю интерпретатор, импортируйте модуль и введите: {{Х0}} затем print break_words(sentence)

Я получаю вышеупомянутую ошибку.

И да, я понимаю, что это избыточно, я просто играю с функциями.

Правка 2. Вот полный след.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ex25.py", line 6, in break_words
words = stuff.split(' ')

Изменить 3: я не знаю, что я сделал по-другому, но когда я попробовал это снова сейчас, это сработало:

>>> s = "sdfd dfdf ffff"
>>> ex25.break_words(s)
['sdfd', 'dfdf', 'ffff']
>>> words = ex25.break_words(s)
>>>

Как видите, ошибок нет.

7 ответов

Лучший ответ

У вас была та же проблема в этом упражнении из «Питона на харвее». Я просто должен был поставить пробел между кавычками.

def breakWords(stuff):
    """this function will break up words."""
    words = stuff.split(" ")
    return words

Также, как кто-то упомянул, вы должны перезагрузить модуль. хотя в этом примере, поскольку с помощью командной строки в windows мне пришлось выйти (), затем перезапустить сеанс py и снова импортировать упражнение.


8

Sotos
30 Июн 2017 в 09:05

Как показано ниже в выводе отладчика, эта ошибка генерируется пустым параметром для разделения

>>> s="abc def ghi jkl"
>>> s.split(" ")
['abc', 'def', 'ghi', 'jkl']
>>> s.split("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> 

Ваш код должен передавать пустое значение для разделения. Исправьте это, и ошибка исчезнет.


3

Vorsprung
29 Дек 2013 в 16:08

enter image description here


  1. Добавьте туда пробел: words = stuff.split(" ")

  2. Перезагрузите ваш переводчик


0

Eldad Assis
2 Июн 2016 в 07:30

Я получил проблему, похожую на ту же ошибку.

Но дело в том, что я пропустил пробел в функции split (» «). # Значение Ошибка: Пустой разделитель

Если вы вставите пробел между апострофами, ошибка будет исправлена


0

Kathiravan Natarajan
18 Май 2017 в 20:50

У меня была точно такая же проблема. Первоначальная ошибка произошла из-за пустого разделителя », который я забыл вставить в него. После того, как вы изменили код, вам нужно выйти из Python, а затем перезапустить Python и импортировать ex25. Это будет работать. Если вы не выходите из Python и просто импортируете код снова, он не будет работать. Или самый простой способ — перезагрузить (ex25), тогда это решит проблему. Надеюсь, что это может помочь


0

cansdmz
10 Фев 2017 в 21:36

Вам определенно не нужны кавычки в скобках.

sentence = "bla mla gla dla"
sentence.split()

Дам тебе

[‘bla’, ‘mla’, ‘gla’, ‘dla’]

В результате по умолчанию.


0

diamind
15 Июл 2019 в 02:40

У меня была та же проблема, когда я учился по книге — изучать Python трудным путем,

Удаление 2 апостроф («») решило проблему для меня.

Words = stuff.split () # удаление апострофов устраняет ошибку


0

Alex
8 Мар 2017 в 08:34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

upworkap opened this issue

Mar 2, 2020

· 1 comment

Comments

@upworkap

Is it possible to use scrapy shell and paste non-ascii characters?
I think it is related to IPython.

@nyov

2 participants

@nyov

@upworkap

4 ответа

Используйте list():

>>> list('1111')
['1', '1', '1', '1']

В качестве альтернативы вы можете использовать map():

>>> map(None, '1111')
['1', '1', '1', '1']

Разница во времени:

$ python -m timeit "list('1111')"
1000000 loops, best of 3: 0.483 usec per loop
$ python -m timeit "map(None, '1111')"
1000000 loops, best of 3: 0.431 usec per loop

TerryA
29 июнь 2013, в 14:39

Поделиться

Можно напрямую записывать строки для

>>> list('1111')
['1', '1', '1', '1']

или использования списков

>>> [i for i in '1111']
['1', '1', '1', '1']

второй способ может быть полезен, если вы хотите разделить строки на подстроки длиной более 1 символа

>>> some_string = '12345'
>>> [some_string[i:i+2] for i in range(0, len(some_string), 2)]
['12', '34', '5']

oleg
29 июнь 2013, в 14:42

Поделиться

Строки являются итерабельными и могут быть проиндексированы, поэтому вам совсем не нужно разделить его:

>>> for char in '11111':
...   print char
... 
1
1
1
1
1
>>> '11111'[4]
'1'

Вы можете «разбить» его на вызов в список, но это не имеет большого значения:

>>> for char in list('11111'):
...   print char
... 
1
1
1
1
1
>>> list('11111')[4]
'1'

Поэтому вам нужно сделать это, только если ваш код явно ожидает список. Например:

>>> list('11111').append('2')
>>> l = list('11111')
>>> l.append(2)
>>> l
['1', '1', '1', '1', '1', 2]

Это не работает с прямой строкой:

>>> l.append('2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

В этом случае вам понадобится:

>>> l += '2'
>>> l
'111112'

Lennart Regebro
29 июнь 2013, в 15:46

Поделиться

Метод # 1:

s="Amalraj"
l=[i for i in s]
print(l)

Вывод:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Способ №2:

s="Amalraj"
l=list(s)
print(l)

Вывод:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Способ № 3:

import re; # importing regular expression module
s="Amalraj"
l=re.findall('.',s)
print(l)

Вывод:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Amalraj Victory
04 июнь 2017, в 15:02

Поделиться

Ещё вопросы

  • 1Как соединить 2 разных счетчика
  • 1Страница не перенаправляет должным образом весеннюю безопасность
  • 1Spotify Web API — ошибка 400 без тела при создании списка воспроизведения
  • 0Как я могу удалить пустой массив
  • 0Как правильно создать этот тип макета (содержащий PHP)
  • 1Разрешение DNS с другим (произвольным) DNS-сервером
  • 1Установите область просмотра, чтобы соответствовать физическим пикселям
  • 1Мне нужна ссылка, которая сначала сохраняет переменную в сессии, а затем открывает новую вкладку
  • 1Как построить новый граф в уже существующем matplotlib
  • 0Включить URI для ресурса в ответ API
  • 1Попытка построить репозиторий Neo4j
  • 1Куда я иду не так, когда соответствует времени?
  • 0Где В + Рэнд () + Лимит
  • 0MySQL группа, два условия, предел 1
  • 1Spark: заменить нулевые значения в кадре данных на среднее значение столбца
  • 0Добавьте html-тег к результату переменной jQuery
  • 0Jquery с AJAX, не вызывая действие и не отображая вывод. Но, в состоянии сделать со старым способом без AJAX
  • 1Есть ли способ вставить список в метод .format в python? [Дубликат]
  • 1Индексация Mongodb должна быть переопределена каждый раз
  • 1Android-приложение, ошибка «источник не найден» — попытался загрузить исходный код Android
  • 0Неправильное использование индекса MySQL для похожих таблиц: «Использование индекса» и «Использование где; Используя index ‘
  • 0Аутентификация углового интерфейса при использовании Grails и Spring Security для бэкенда
  • 0Дисплей можно перетаскивать из div с дисплеем, установленным на none
  • 0Слайдер не показывает заголовки для сгенерированных клонов
  • 0Jquery Loop останавливается после 2-го элемента
  • 1Используя Beautifulsoup, как извлечь информацию, которая не встроена в теги
  • 0Слайдер / мастер, который ведет к определенной странице на основе сделанного выбора
  • 1код JavaScript работает только один раз, когда страница загружена
  • 1Формат даты и времени / Шаблоны в классе Java / SimpleDateFormat
  • 1Android OpenGL профилирование использования памяти?
  • 0JQuery всплывающее окно не работает — простое настраиваемое всплывающее окно
  • 1красивый цикл, вложенный в функцию dict: как это работает?
  • 0Angular: Как разделить (разделить) скрипт контроллера? [Дубликат]
  • 0Перегрузка << и >> хорошо работает с указателями C ++
  • 0Вызов переменной javascript внутри кода ac #
  • 1Группировка массивов и получение последнего и первого массива для каждой группы
  • 0Запустите ./script.sh из PHP
  • 1кодировка UTF 8 Java JDBC оракул
  • 0DSO ссылается на скрытый символ fstat64 в /usr/lib/libc_nonshared.a(fstat64.oS)
  • 1SpecsFor MVC / MSBuild.exe неправильно строит / публикует проект в Visual Studio 2012
  • 1Вызов кодов за другим был закончен node.js
  • 1WPF список с разными цветами
  • 1Как получить вывод из класса после ввода всех значений
  • 1Элементы PriorityQueue не упорядочены [дубликаты]
  • 1Как изменить местоположение, в котором свойства зависимостей появляются в окне свойств дизайнера WPF?
  • 1Список файлов, начиная с папки src
  • 1Создание объекта подкласса аккаунта
  • 0MYSQL Inner Join, возвращающий повторяющиеся результаты (уже используя DISTINCT)
  • 0Angular JS — передача области видимости
  • 0Jquery Выбранный класс

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Eps ошибка фольксваген что это значит
  • Emps u0105 ошибка тойота