Python split without empty strings

Python Regex Split без пустой строки

Скажите формулировка задачи, вы используете функцию Re.Split (Pattern, String) для разделения строки на все вхождения данного шаблона. Если шаблон появляется в начале или в конце строки, полученный список разделений будет содержать пустые строки. Как избавиться от пустых струн автоматически? Вот пример: Import Re … Python Regex Split без пустой строки Подробнее »

Постановка проблемы

Скажи, вы используете Re.Split (шаблон, строка) Функция для разделения строки на все вхождения данного шаблона. Если шаблон появляется в начале или в конце строки, полученный список разделений будет содержать пустые строки. Как избавиться от пустых струн автоматически?

import re s = '--hello-world_how are\tyou-----------today\t' words = re.split('[-_\s]+', s) print(words) # ['', 'hello', 'world', 'how', 'are', 'you', 'today', '']

Обратите внимание на пустые строки в результирующемся списке.

Фон

Re.Split (шаблон, строка) Метод соответствует всем вхождению шаблон В строка и делит строку вдоль матчей, что приводит к списку строк между матчи. Например, Re.Split («A», «BBABBBAB») Результаты в списке строк [«BB», «BBB», «B»] – и Re.Split («А», «Аббандбаба») Результаты в списке строк [», «BB», «BBB», «B», »] с пустыми струнами.

Связанная статья: Python Regex Split.

Способ 1: Удалите все пустые строки из списка с использованием понимания списка

Тривиальное решение этой проблемы состоит в том, чтобы Удалить все пустые строки Из полученного списка с использованием Понимание списка с условием такие как [X для X в словах, если] к Фильтр из пустой строки.

import re s = '--hello-world_how are\tyou-----------today\t' # Method 1: Remove all Empty Strings From the List words = re.split('[-_\s]+', s) words = [x for x in words if x!=''] print(words) # ['hello', 'world', 'how', 'are', 'you', 'today']

Способ 2: Удалите все пустые строки из списка с помощью фильтра ()

Альтернативное решение – это Удалить все пустые строки Из полученного списка с использованием Фильтр () такие как Фильтр (бул, слова) к Фильтр из пустой строки » и другие элементы, которые оценивают в Ложь такие как Нет Отказ

import re s = '--hello-world_how are\tyou-----------today\t' # Method 2: Remove Empty Strings From List using filter() words = re.split('[-_\s]+', s) words = list(filter(bool, words)) print(words) # ['hello', 'world', 'how', 'are', 'you', 'today']

Способ 3: Используйте Re.findall () Вместо

Простой и пифитоновый раствор – использовать Re.findall (шаблон, строка) С обратной структурой, используемой для разделения списка. Если шаблон A используется в качестве разделенного шаблона, все, что не соответствует шаблону A, может использоваться в Re.findall () Функция, чтобы по существу извлекать список разделений.

Читайте также:  Working with files python programming

Вот пример, который использует Отрицательный класс символов [^ -_ \ s] + Чтобы найти все символы, которые не соответствуют разбитому шаблону:

import re s = '--hello-world_how are\tyou-----------today\t' # Method 3: Use re.findall() words = re.findall('([^-_\s]+)', s) print(words)

Результатом является тот же список разделений:

['hello', 'world', 'how', 'are', 'you', 'today']

Куда пойти отсюда?

Достаточно теории, давайте познакомимся!

Чтобы стать успешным в кодировке, вам нужно выйти туда и решать реальные проблемы для реальных людей. Вот как вы можете легко стать шестифункциональным тренером. И вот как вы польские навыки, которые вам действительно нужны на практике. В конце концов, что такое использование теории обучения, что никто никогда не нуждается?

Практические проекты – это то, как вы обостряете вашу пилу в кодировке!

Вы хотите стать мастером кода, сосредоточившись на практических кодовых проектах, которые фактически зарабатывают вам деньги и решают проблемы для людей?

Затем станьте питоном независимым разработчиком! Это лучший способ приближения к задаче улучшения ваших навыков Python – даже если вы являетесь полным новичком.

Присоединяйтесь к моему бесплатным вебинаре «Как создать свой навык высокого дохода Python» и посмотреть, как я вырос на моем кодированном бизнесе в Интернете и как вы можете, слишком от комфорта вашего собственного дома.

Присоединяйтесь к свободному вебинару сейчас!

Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.

Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.

Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.

Читайте ещё по теме:

Источник

Python split ignore empty | How to ignore empty spaces – Example code

Splitting a string can sometimes give empty strings returned in the Python split() method.

For example, how Python split method to return list with empty space.

str1 = '/segment/segment/'.split('/') print(str1) 

Python split ignore empty

More generally, to remove empty strings returned in split() results, you may want to look at the filter function.

f = filter(None, '/segment/segment/'.split('/')) s_all = list(f) print(s_all)

Output: [‘segment’, ‘segment’]

How to Python split ignore the empty example

Python simple example code. As per upper code, it was only one type of problem but in real-time there can be more.

Method 1: Example Remove all Empty Strings From the List using List Comprehension

import re s = '--hello-world_how are\tyou-----------today\t' words = re.split('[-_\s]+', s) print(words) words = [x for x in words if x != ''] print(words) 

Remove all Empty Strings From the List using List Comprehension

Method 2: Example Remove all Empty Strings From the List using filter()

import re s = '--hello-world_how are\tyou-----------today\t' words = re.split('[-_\s]+', s) words = list(filter(bool, words)) print(words)

Method 3: Example use re.findall() Instead

import re s = '--hello-world_how are\tyou-----------today\t' words = re.findall('([^-_\s]+)', s) print(words) 

Do comment if you have any doubts and suggestions on this Python split topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Источник

Читайте также:  Java for centos 7

Python Regex Split Without Empty String

Be on the Right Side of Change

Say, you use the re.split(pattern, string) function to split a string on all occurrences of a given pattern. If the pattern appears at the beginning or the end of the string, the resulting split list will contain empty strings. How to get rid of the empty strings automatically?

import re s = '--hello-world_how are\tyou-----------today\t' words = re.split('[-_\s]+', s) print(words) # ['', 'hello', 'world', 'how', 'are', 'you', 'today', '']

Note the empty strings in the resulting list.

Background

The re.split(pattern, string) method matches all occurrences of the pattern in the string and divides the string along the matches resulting in a list of strings between the matches. For example, re.split(‘a’, ‘bbabbbab’) results in the list of strings [‘bb’, ‘bbb’, ‘b’] —and re.split(‘a’, ‘abbabbbaba’) results in the list of strings [», ‘bb’, ‘bbb’, ‘b’, »] with empty strings.

Related Article: Python Regex Split

Method 1: Remove all Empty Strings From the List using List Comprehension

The trivial solution to this problem is to remove all empty strings from the resulting list using list comprehension with a condition such as [x for x in words if x!=»] to filter out the empty string.

import re s = '--hello-world_how are\tyou-----------today\t' # Method 1: Remove all Empty Strings From the List words = re.split('[-_\s]+', s) words = [x for x in words if x!=''] print(words) # ['hello', 'world', 'how', 'are', 'you', 'today']

Method 2: Remove all Empty Strings From the List using filter()

An alternative solution is to remove all empty strings from the resulting list using filter() such as filter(bool, words) to filter out the empty string » and other elements that evaluate to False such as None .

import re s = '--hello-world_how are\tyou-----------today\t' # Method 2: Remove Empty Strings From List using filter() words = re.split('[-_\s]+', s) words = list(filter(bool, words)) print(words) # ['hello', 'world', 'how', 'are', 'you', 'today']

Method 3: Use re.findall() Instead

A simple and Pythonic solution is to use re.findall(pattern, string) with the inverse pattern used for splitting the list. If pattern A is used as a split pattern, everything that does not match pattern A can be used in the re.findall() function to essentially retrieve the split list.

Here’s the example that uses a negative character class [^-_\s]+ to find all characters that do not match the split pattern:

import re s = '--hello-world_how are\tyou-----------today\t' # Method 3: Use re.findall() words = re.findall('([^-_\s]+)', s) print(words)

The result is the same split list:

['hello', 'world', 'how', 'are', 'you', 'today']

Where to Go From Here?

Enough theory. Let’s get some practice!

Читайте также:  Javascript change select option values

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Be on the Right Side of Change 🚀

  • The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
  • Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
  • Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.

Learning Resources 🧑‍💻

⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!

Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.

New Finxter Tutorials:

Finxter Categories:

Источник

Оцените статью