Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,124
» Latest member: codestar101
» Forum threads: 21,772
» Forum posts: 22,641

Full Statistics

Online Users
There are currently 559 online users.
» 0 Member(s) | 555 Guest(s)
Applebot, Baidu, Bing, Google

 
  [Tut] Python | Split String with Regex
Posted by: xSicKxBot - 12-13-2022, 06:04 AM - Forum: Python - No Replies

Python | Split String with Regex

Rate this post

Summary: The different methods to split a string using regex are:

  • re.split()
  • re.sub()
  • re.findall()
  • re.compile()

Minimal Example


import re text = "Earth:Moon::Mars:Phobos" # Method 1
res = re.split("[:]+", text)
print(res) # Method 2
res = re.sub(r':', " ", text).split()
print(res) # Method 3
res = re.findall("[^:\s]+", text)
print(res) # Method 4
pattern = re.compile("[^:\s]+").findall
print(pattern(text)) # Output
['Earth', 'Moon', 'Mars', 'Phobos']

Problem Formulation


?Problem: Given a string and a delimiter. How will you split the string using the given delimiter using different functions from the regular expressions library?

Example: In the following example, the given string has to be split using a hyphen as the delimiter.

# Input
text = "abc-lmn-xyz" # Expected Output
['abc', 'lmn', 'xyz']

Method 1: re.split


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'].


Approach: Use the re.split function and pass [_]+ as the pattern which splits the given string on occurrence of an underscore.

Code:

import re text = "abc_lmn_xyz"
res = re.split("[_]+", text)
print(res) # ['abc', 'lmn', 'xyz']

?Related Read: Python Regex Split

Method 2: re.sub


The regex function re.sub(P, R, S) replaces all occurrences of the pattern P with the replacement R in string S. It returns a new string. For example, if you call re.sub('a', 'b', 'aabb'), the result will be the new string 'bbbb' with all characters 'a' replaced by 'b'.


Approach: The idea here is to use the re.sub function to replace all occurrences of underscores with a space and then use the split function to split the string at spaces.

Code:

import re text = "abc_lmn_xyz"
res = re.sub(r'_', " ", text).split()
print(res) # ['abc', 'lmn', 'xyz']

?Related Read: Python Regex Sub

Method 3: re.findall


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.


Approach: Find all occurrences of characters that are separated by underscores using the re.findall().

Code:

import re text = "abc_lmn_xyz"
res = re.findall("[^_\s]+", text)
print(res) # ['abc', 'lmn', 'xyz']

?Related Read: Python re.findall()

Method 4: re.compile


The method re.compile(pattern) returns a regular expression object from the pattern that provides basic regex methods such as pattern.search(string)pattern.match(string), and pattern.findall(string). The explicit two-step approach of (1) compiling and (2) searching the pattern is more efficient than calling, say, search(pattern, string) at once, if you match the same pattern multiple times because it avoids redundant compilations of the same pattern.


Code:

import re text = "abc_lmn_xyz"
pattern = re.compile("[^-\s]+").findall
print(pattern(text)) # ['abc', 'lmn', 'xyz']

Why use re.compile?


  • Efficiency: Using re.compile() to assemble regular expressions is effective when the expression has to be used more than once. Thus, by using the classes/objects created by compile function, we can search for instances that we need within different strings without having to rewirte the expressions again and again. This increases productivity as well as saves time.
  • Readability: Another advantage of using re.compile is the readability factor as it leverages you the power to decouple the specification of the regex.

?Read: Is It Worth Using Python’s re.compile()?

Exercise


Problem: Python regex split by spaces, commas, and periods, but not in cases like 1,000 or 1.50.

Given:
my_string = "one two 3.4 5,6 seven.eight nine,ten"
Expected Output:
["one", "two", "3.4", "25.6" , "seven", "eight", "nine", "ten"]

Solution

my_string = "one two 3.4 25.6 seven.eight nine,ten"
res = re.split('\s|(?<!\d)[,.](?!\d)', my_string)
print(res) # ['one', 'two', '3.4', '25.6', 'seven', 'eight', 'nine', 'ten']

Conclusion


Therefore, we have learned four different ways of splitting a string using the regular expressions package in Python. Feel free to use the suitable technique that fits your needs. The idea of this tutorial was to get you acquainted with the numerous ways of using regex to split a string and I hope it helped you.

Please stay tuned and subscribe for more interesting discussions and tutorials in the future. Happy coding! ?


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.



https://www.sickgaming.net/blog/2022/12/...ith-regex/

Print this item

  (Indie Deal) PJ Sam & Golazo Giveaways, Neptunuia & TMNT Deals
Posted by: xSicKxBot - 12-13-2022, 06:04 AM - Forum: Deals or Specials - No Replies

PJ Sam & Golazo Giveaways, Neptunuia & TMNT Deals

Pajama Sam & Golazo Giveaways
[www.indiegala.com]
https://www.youtube.com/watch?v=8uOX4rDyXBI
Idea Factory Sale, up to 80% OFF
[www.indiegala.com]
https://www.youtube.com/watch?v=9pHFNsBuA28
https://www.youtube.com/watch?v=1kPdvJWhXAA
[discord.gg]


https://steamcommunity.com/groups/indieg...3313485452

Print this item

  (Free Game Key) Ghost of a tale - Free GOG Game Giveaway
Posted by: xSicKxBot - 12-13-2022, 06:04 AM - Forum: Deals or Specials - No Replies

Ghost of a tale - Free GOG Game Giveaway

This giveaway is on gog.com gog is a platform for games that is dedicated to drm-free games (those are games that do not require login or registration to play the game)

How to grabGhost of a tale
- Go to the home page of https://gog.com/#giveaway
- Login and Register
- Go to the home page again
- Wait for 10 seconds then start searching for Ghost of a tale
- on the home page look for "Deal of the Day" (above it there should be a banner)
- on the banner there is a button "Yes, and claim the game" click it
- Thats it


GOG Store link: https://www.gog.com/game/ghost_of_a_tale
Auto-claim link: https://www.gog.com/giveaway/claim

We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.

?GrabFreeGames.com ?Twitter ?Steam Curator ?Facebook[fb.me]?Discord[discord.gg]
❤️Support us: HumbleBundle Partner[www.humblebundle.com] Fanatical Affiliate[www.fanatical.com]


https://steamcommunity.com/groups/GrabFr...3054866631

Print this item

  News - Elden Ring: Where To Get The Coil Shield
Posted by: xSicKxBot - 12-13-2022, 06:04 AM - Forum: Lounge - No Replies

Elden Ring: Where To Get The Coil Shield

Though you can technically use them to deal damage, most shields in Elden Ring are, well, meant for doing things shields tend to do, like blocking and parrying. In the case of the Coil Shield, though, there's a very special skill attached that can be a lot of fun for poison-based builds--and it looks cool to boot. If that sounds fun to you, read on to find out where you can pick it up.

The Coil Shield explained

The Coil Shield is a small shield that requires 10 Strength and 10 Dexterity to wield. Its unique weapon skill is Viper Bite, which can be activated to deal a bit of damage and inflict poison buildup on enemies, making it a truly unique shield.

The Coil Shield's item description reads:

Continue Reading at GameSpot

https://www.gamespot.com/articles/elden-...01-10abi2f

Print this item

  PC - Soccer Story
Posted by: xSicKxBot - 12-13-2022, 06:04 AM - Forum: New Game Releases - No Replies

Soccer Story



It's been a year since The Calamity tore apart the very foundations of soccer as we know it, and since then, Soccer Inc. has made dang well sure that not a soul has been allowed to even look at a soccer ball, let alone kick it.

Soccer may have been banned across the world... but now there is hope! A magical soccer ball has chosen you, our Savior of Soccer!

Soccer Story is a physics-driven adventure RPG, where every problem can be solved with your trusty magic ball. Along the way, you'll need to best bad guys in 1v1s, compete in a range of different sports (with your soccer ball, of course), and sometimes use your brain just as much as your balls

In a world that has long forgotten The Beautiful Game, can you remind them why soccer is top of the table, and best the most formidable teams, including the local toddlers and a group of sharks?

Publisher: No More Robots

Release Date: Nov 29, 2022




https://www.metacritic.com/game/pc/soccer-story

Print this item

  [Tut] How to Split a Multi-line String into Multiple Lines?
Posted by: xSicKxBot - 12-12-2022, 09:10 AM - Forum: Python - No Replies

How to Split a Multi-line String into Multiple Lines?

Rate this post

Summary: Use given_string.splitlines() to split a given multiline string into multiple lines.

Minimal Example:

text = 'Python\nJava\nC#'
print(text.splitlines())
# Output: ['Python', 'Java', 'C#']

Problem Formulation


?Problem: Given a string, How will you split the string into a list of words using newline as a separator/delimiter?

Example:


# Input
text = """abc
def
ghi """
# Expected Output
['abc', 'def', 'ghi']

Let’s dive into the different ways of solving the given problem.

Method 1: Using splitlines


Approach: The most convenient and easiest way to split a given multiline string into multiple strings is to use the splitlines() method, i.e., simply use – 'given_string'.splitlines().

NOTE: splitlines() is a built-in method in Python that splits a string at line breaks such as '\n' and returns a split list of substrings (i.e., lines). For example, 'finxter\nis\ncool'.splitlines() will return the following list: ['finxter', 'is', 'cool'].

Code:

# Input
text = """Python is an Object Oriented programming language.
COBOL is an Object Oriented programming language.
F# is an Object Oriented programming language.""" print(text.splitlines()) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']

?Related Read: Python String splitlines()

Method 2: Using split()


Approach: Use 'given_string'.split('\n') to split the given multiline string at line breaks.

Code:

# Input
text = """Python is an Object Oriented programming language.
COBOL is an Object Oriented programming language.
F# is an Object Oriented programming language.""" print(text.split('\n')) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']

Using “\n” ensures that whenever a new line occurs, the string is split.

?Related Read: Python String split()

Method 3: Using re.split in a List Comprehension


Another way to solve the given problem is to use the split method of the regex module. You can split the string at every line break by passing “\n” as the pattern within the re.split function. To ensure that there are no leading or trailing extra whitespaces in the resultant list you can use a list comprehension that stores the split strings only and eliminates whitespace characters. This can be done with the help of an if statement within the list comprehension as shown in the solution below.

Code:

import re text = """Python is an Object Oriented programming language.
COBOL is an Object Oriented programming language.
F# is an Object Oriented programming language.""" print([x for x in re.split("\n", text) if x!='']) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']

NOTE: 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'].

?Read more here – Python Regex Split

List Comprehension: “A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.”

?Read more here: List Comprehension in Python — A Helpful Illustrated Guide


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


We have successfully solved the given problem using three different approaches. I hope you this article answered all your queries. Please subscribe and stay tuned for more interesting articles!

Happy coding! ?

Related Reads:
⦿ Python | Split String by Newline
⦿ Python | Split String by Whitespace
⦿ Python | Split String into Characters


Python Regex Course


Google engineers are regular expression masters. The Google search engine is a massive text-processing engine that extracts value from trillions of webpages.  

Facebook engineers are regular expression masters. Social networks like Facebook, WhatsApp, and Instagram connect humans via text messages

Amazon engineers are regular expression masters. Ecommerce giants ship products based on textual product descriptions.  Regular expressions ​rule the game ​when text processing ​meets computer science. 

If you want to become a regular expression master too, check out the most comprehensive Python regex course on the planet:




https://www.sickgaming.net/blog/2022/12/...ple-lines/

Print this item

  (Indie Deal) FREE Gravity Den, Horizon Zero Dawn, Game Awards Sale ending soon
Posted by: xSicKxBot - 12-12-2022, 09:10 AM - Forum: Deals or Specials - No Replies

FREE Gravity Den, Horizon Zero Dawn, Game Awards Sale ending soon

Gravity Den FREEbie
[freebies.indiegala.com]
Change the gravity on the ground & help Dan reach the lost ship.

https://www.youtube.com/watch?v=76O5KaJHEA0
The Game Awards Sale ending soon
[www.indiegala.com]
https://youtu.be/ODwLA7qgv-U
[www.indiegala.com]


https://steamcommunity.com/groups/indieg...3310941702

Print this item

  News - Armored Core 6: Fires Of Rubicon Announced At The Game Awards
Posted by: xSicKxBot - 12-12-2022, 09:10 AM - Forum: Lounge - No Replies

Armored Core 6: Fires Of Rubicon Announced At The Game Awards

A new From Software game was announced at this year's Game Awards, but it's not another iteration of the Soulsbornes we've come to expect from the studio. Instead From is going back to its roots with a new entry in its mecha shooter series, called Armored Core VI: Fires of Rubicon.

The brief teaser trailer showed a ruined world followed by some glamor shots of big stompy robots, as well as other giant mechanized behemoths, which is what you would want from a mecha game.


https://www.gamespot.com/articles/armore...01-10abi2f

Print this item

  PC - Gungrave G.O.R.E
Posted by: xSicKxBot - 12-12-2022, 09:10 AM - Forum: New Game Releases - No Replies

Gungrave G.O.R.E



In Gungrave G.O.R.E, play the gun-wielding badass anti-hero of your dreams as you mow down tons of enemies in a gory ballet of bullets and experience a story of vengeance, love and loyalty, all in a beautiful third-person action shooter, combining the best that Eastern and Western game design have to offer.

As the titular Gunslinger of Resurrection, you become the badass anti-hero of your dreams, an ultimate killing machine, brutalising your foes without mercy. Taking cover and retreating is not an option for Grave, he only ever goes full steam ahead, preferably right through his enemies.

Stylish third-person shooting meets close-range martial arts, creating seamlessly flowing action as you crush your enemies in a gory ballet of bullets. Utilise your unlimited ammo Cerberus pistols and your transformable EVO-coffin to unleash devastating combos in pursuit of maximum damage and style.

Publisher: Prime Matter

Release Date: Nov 22, 2022




https://www.metacritic.com/game/pc/gungrave-gore

Print this item

  [Oracle Blog] Apache Spark—Lightning fast on GraalVM Enterprise
Posted by: xSicKxBot - 12-11-2022, 12:17 PM - Forum: Java Language, JVM, and the JRE - No Replies

Apache Spark—Lightning fast on GraalVM Enterprise

Discover how Apache Spark runs faster and uses less memory with GraalVM Enterprise.


https://blogs.oracle.com/java/post/apach...enterprise

Print this item

 
Latest Threads
Temu Promo Code For New U...
Last Post: codestar101
56 minutes ago
[Verified] 30% Off Temu C...
Last Post: codestar101
57 minutes ago
Temu Coupon Code 30% OFF ...
Last Post: codestar101
58 minutes ago
How To Get Temu Coupon Co...
Last Post: codestar101
1 hour ago
Temu Coupon Code 30% Off ...
Last Post: codestar101
1 hour ago
New Temu Coupon Code [ald...
Last Post: codestar101
1 hour ago
Temu Coupon Code 30% Off ...
Last Post: codestar101
1 hour ago
Temu Coupon 30%Off Code [...
Last Post: codestar101
1 hour ago
Cupones Para Temu [ald911...
Last Post: Bebeckman6
1 hour ago
Codice Coupon Temu Primo ...
Last Post: Bebeckman6
1 hour ago

Forum software by © MyBB Theme © iAndrew 2016