Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[-]
Welcome
You have to register before you can post on our site.

Username:


Password:





[-]
Discord Widget

[-]
Twitter: SickGaming

[-]
Latest Threads
[Oracle Blog] What’s New in Java Managem...
Last Post: xSicKxBot
Today 06:51 AM
» Replies: 0
» Views: 7
[Tut] How to Flush Your Cache on Windows...
Last Post: xSicKxBot
Today 06:51 AM
» Replies: 0
» Views: 5
(Indie Deal) Match3 Love Bundle & MechWa...
Last Post: xSicKxBot
Today 06:51 AM
» Replies: 0
» Views: 5
PC - Backfirewall_
Last Post: xSicKxBot
Today 06:51 AM
» Replies: 0
» Views: 5
[Oracle Blog] JavaOne is Back!
Last Post: xSicKxBot
Yesterday 12:34 PM
» Replies: 0
» Views: 10
[Tut] How I Built a House Price Predicti...
Last Post: xSicKxBot
Yesterday 12:33 PM
» Replies: 0
» Views: 8
[Tut] How to Install phpMyAdmin on a Win...
Last Post: xSicKxBot
Yesterday 12:33 PM
» Replies: 0
» Views: 8
(Indie Deal) PlayStation Sale: God of Wa...
Last Post: xSicKxBot
Yesterday 12:33 PM
» Replies: 0
» Views: 7
News - New Marvel Book Details The MCU's...
Last Post: xSicKxBot
Yesterday 12:33 PM
» Replies: 0
» Views: 7
PC - Marvel's Midnight Suns - The Good, ...
Last Post: xSicKxBot
Yesterday 12:33 PM
» Replies: 0
» Views: 7

[Tut] Python | Split String Empty Separator

#1
Python | Split String Empty Separator

Rate this post

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:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\Blogs\Finxter.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)



https://www.sickgaming.net/blog/2022/11/...separator/
Reply





Users browsing this thread:
1 Guest(s)

𝚂̷𝚒̷𝚌̷𝚔̷𝙶̷𝚊̷𝚖̷𝚒̷𝚗̷𝚐̷ 𝙷̷𝚘̷𝚖̷𝚎̷

Copyright © SickGaming.net 2022