Reducing boilerplate in string generation functions in python
If you have repetitive code that generates strings you can greatly reduce boilerplate by using the function locals(), which returns a dictionary with the current local variables in a function, and the format() method, which is the current preferred method for string formatting.
As an example, consider the following function:
def generate_address(street, number, district, city, state, zipcode):
address = """
{street}, {number} - {district}
{city} - {state} {zipcode}
""".format(**locals())
return address
Written by Rafael Calsaverini
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#