Making a destructurable list of value
I love this one and it makes me think about the destructuring in JavaScript.
With Tuple[type, type]
and a wrapping it in a list, you can use a for...of
loop:
|
|
Replacing Substrings in Strings
To replace a substring in a string, you can use the replace()
method. Here’s how you can replace http
with https
in Python:
|
|
This will output:
|
|
The third argument is the number of times you want to replace the target substring. Very handy!
Sanitizing A String
Let say you have an endpoint in a REST API that must return an XML response.
Now the content of the XML response looks like the following:
|
|
The code above represents an endpoint to return call instructions Twilio must speak to the person called.
As it stands right now, the <say-as interpret-as="telephone">
and </say-as>
will become encoded when Twilio receives it. That won’t give the expected result.
To avoid that, you need to tell Flask that message
contains markup and that it shouldn’t be encoded.
However, the caller
value is coming from outside, so we need to sanitize it.
The end result becomes:
|
|
Markup
makes sure the <say-as>
opening and closing tags aren’t encoded and the escape
method sanitizes the caller
value since it comes from outside. Never trust outside sources.
str
vs LiteralString
The Differences
The main differences between str
and LiteralString
in Python are:
- Purpose:
str
is the built-in string type in Python.LiteralString
is a type hint introduced in Python 3.11 for static type checking.
- Usage:
str
is used for actual string objects in Python code.LiteralString
is used in type annotations to indicate that a string is known at compile time.
- Runtime behavior:
str
is a concrete type that exists at runtime.LiteralString
is erased at runtime and doesn’t affect program execution.
- Type checking:
LiteralString
is more restrictive thanstr
in type checking.
Here’s an example to illustrate:
|
|
In this example, safe_query
only accepts LiteralString
, which helps prevent SQL injection by ensuring only literal strings are used for queries.
How do you convert a LiteralString to str in python
To convert a LiteralString to a regular str in Python, you can simply use the built-in str()
function. Here’s how you can do it:
|
|
Encoding URL In Python
To encode a URL in Python, you can use the urllib.parse.quote()
function. Here’s how you can do it:
|
|
This will output:
|
|
Accessing Query String in Flask 3 POST Requests
To get the query string values from a POST request with the Content-Type application/x-www-form-urlencoded
in Flask 3, you can use the request.form
object. Here’s how you can do it:
|
|
In this example:
- We import
request
from Flask. - We define a route that accepts POST requests.
- Inside the route handler, we use
request.form
to access the form data. - You can get specific values using
request.form.get('key')
. To avoid possible errors, you can use the default parameter in the second parameter of theget
method:request.form.get('key', None)
. - Alternatively, you can iterate through all form data using a loop.
Remember that request.form
is a MultiDict, so if you expect multiple values for the same key, you can use request.form.getlist('key')
.
Switch…case
Python doesn’t have a built-in switch…case statement like some other programming languages, but there are a few ways to achieve similar functionality:
Using dictionaries (most common approach)
|
|
Using if-elif-else statements
|
|
Using Python 3.10+ match-case statement
That’s the closest to the switch...case
you probably know.
|
|
The dictionary method is often preferred for its simplicity and efficiency. The match-case statement is a newer feature and provides more advanced pattern matching capabilities.
Subtracting Time From a Datetime
To remove a day from a datetime
object in Python, you can use the timedelta
class from the datetime
module. Here’s how you can do it:
|
|
This code will subtract one day from the given date. If you want to remove more than one day, you can change the days
parameter in the timedelta
function.
Removing the First Item From a Python List
This one is pretty cool. You have 3 ways to do it and coming from years of .NET programming in C# or JavaScript, I love how Python enables you to perform the task.
Using the pop()
method:
This one feels like JavaScript:
|
|
Using list slicing
|
|
Using the del
statement
|
|
Conclusion
Which method do you prefer?
Initializing Datetime with Timezone
You can initialize a datetime
object in Python with a string and a time zone. Here’s how you can do it using the datetime
module and pytz
library:
|
|
This code will create a timezone-aware datetime
object for the specified date and time in the “Europe/Zurich” time zone.
A few things to note:
- You need to install the
pytz
library if you haven’t already. You can do this withpip install pytz
. - The
strptime
method parses the string according to the format you specify. Make sure your format string matches your input string. - The
localize
method of the time zone object is used to attach the time zone information to thedatetime
object. - If you want to convert this
datetime
to another time zone, you can use theastimezone
method.
Get the Index In A For … In Loop
To get the index in a for loop, you can use the enumerate()
function in Python. Here’s a simple example:
|
|
This code will output:
|
|
The enumerate()
function returns pairs of (index, item) for each item in the iterable. You can then use these values directly in your loop.
If you want to start the index from a number other than 0, you can pass a start parameter to enumerate()
. For example:
|
|
This will start the indexing from 1 instead of 0.
Accessing Tuple Values by Index
To access values in a tuple from an index, you can use the square bracket notation, just like you would with a list. Here’s how you can access values from the tuples in a sample list:
|
|
In this example, we first access a tuple from the list using its index, then access individual values within the tuple using their respective indices. Remember that tuple indices, like list indices, start at 0.
You can also use tuple unpacking to assign all values to variables at once:
|
|
This assigns each value in the first tuple to a separate variable in order.
Conclusion
You know other tips and cool Python syntax to perform great things? Share them on X!
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Credit: Photo by Pixabay.