Navigation X
ALERT
Click here to register with a few steps and explore all our cool stuff we have to offer!

Cracked.to | Best Forum Around | Free Premium Accounts

 606

[TUTORIAL] Fastest way to parse a string using the LEFT:RIGHT format in Python?

by iclapcheeks - 08 March, 2021 - 06:42 AM
This post is by a banned member (iclapcheeks) - Unhide
295
Posts
102
Threads
2 Years of service
As the title states, you're probably here to find out which is the most efficient and fastest way to parse a string in Python. If so, you've come to the right place.

We'll be conducting 3 different methods listed here:
Code:
Partitioning
Splitting
RegEx (Openbullet Implementation)

Most people might think immediately that RegEx would be the fastest, most efficient, and easiest. Let's take a look at that.

I've already conducted a test using all three of these methods and here is the outcome of each. Each of these test's were all done using the module "timeit" which is a very neat module to quickly test what ithe fastest way of doing something is, accurately. This is not off of a bias of any sort. The test has been repeated 5 times for each method and the average has been calculated.

Results (in seconds):
Code:
Partitioning - 0.42681223999999995
Splitting - 0.5656058800000001
RegEx - 1.92103928

Conclusion?
Partitioning is the fastest and most efficient way of parsing a string. Now, that was quite short. How would you use it in an actual script? Bottoms up, let's dive into that quickly.
Code:
def parse_string(data: str, left: str, right: str) -> str:
    return data.partition(left)[-1].partition(right)[0]

result = parse_string('{"username":"iclapcheeks"}', 'username":"', '"')
print(result)

This is a very simple way of doing it. You can go further into other things such as classes, multi-parsing (multiple elements in one function call), etc. As stated before, this is a very basic and general implementation.

Leave a like if you learned anything.
 
[Image: UD4PKTg.jpg]
[Image: 8QD0LlH.gif]
Thank you @Liars for Premium
Thank you @Azathoth for Premium x2
Thank you @plusrw for Premium x3 
Thank you @Bateman for Infinity
This post is by a banned member (ogbendo) - Unhide
ogbendo  
Infinity
123
Posts
46
Threads
#2
Nice explanation <3
                                          [Image: 2yTY8Dt.gif]
 

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
or
Sign in
Already have an account? Sign in here.


Forum Jump:


Users browsing this thread: 1 Guest(s)