OP 08 March, 2021 - 06:42 AM
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:
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):
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.
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.
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.92103928Conclusion?
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.
Always confirm via PM before dealing with me.