Hello everyone,

When I am coding in Python I often encounter situations where I have a
string like this one.

sample="""
fruit:apple
tree:[Apple tree]
quantity:{5}
quantity:{3}
"""

And I want to grab some kind of value from it.

So let me introduce you to the grab function. This is the definition:

def grab(start, end, list_out=False):

Now, if you want to get the fruit from the sample string you can just
"grab" it as follows:

sample.grab(start="fruit:", end="\n")
>> 'apple'

You can also "grab" values enclosed in brackets or in any kind of character
and It works as you would expect.

sample.grab(start="tree:[", end="]")
>> 'Apple tree'

The optional argument "list_out" makes the function return a list of
values, for cases where there are several of them to grab.

sample.grab(start="quantity:{", end="}", list_out=True)
>> [5, 3]

The "grab" function will return only the first occurrence if "list_out" is
omitted or passed as False.

sample.grab(start="quantity:{", end="}")
>> 5

sample.grab(start="quantity:{", end="}", list_out=False)
>> 5

As you can see, it is incredibly useful for extracting substrings from a
larger and more complex string and can change the way we parse strings for
the better.

For example, it could simplify the way we parse the fields of HTTP headers.
It also has many applications for the parsing of configuration files and
the construction of strings for SQL queries and bash commands among others.

I have implemented this function locally to use it for my personal projects
and It has proven to be really useful in practice, so I hope you find it
useful as well and consider adding it as a class method for strings in
Python.

Julio Cabria
Engineering student
Autonomous University of Madrid
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/NV7G6W4RHTMMVIUDHQAATSVYFRIV6G7Z/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to