Rename language articles

This commit is contained in:
Angelos Chalaris
2023-05-18 23:57:15 +03:00
parent 45d1fa023a
commit 2d58c1dfd7
48 changed files with 17 additions and 17 deletions

View File

@ -0,0 +1,80 @@
---
title: 6 Python f-strings tips and tricks
type: story
language: python
tags: [string]
author: chalarangelo
cover: sea-view
excerpt: Python's f-strings can do a lot more than you might expect. Learn a few useful tips and tricks in this quick guide.
dateModified: 2021-07-20T05:00:00-04:00
---
Python's f-strings provide a more readable, concise and less error-prone way to format strings than traditional string formatting. They are packed with useful features that are sure to come in handy in day-to-day use. Let's take a look at some of them.
### String Interpolation
The most used f-string feature by far is string interpolation. All you need to do is wrap the value or variable in curly braces (`{}`) and you're good to go.
```py
str_val = 'apples'
num_val = 42
print(f'{num_val} {str_val}') # 42 apples
```
### Variable names
Apart from getting a variable's value, you can also get its name alongside the value. This can be especially useful when debugging and can be easily accomplished by adding an equals sign (`=`) after the variable name inside the curly braces.
Bear in mind that whitespace inside the curly braces is taken into account, so adding spaces around the equals sign can make for a more readable result.
```py
str_val = 'apples'
num_val = 42
print(f'{str_val=}, {num_val = }') # str_val='apples', num_val = 42
```
### Mathematical operations
Not syntactically unlike variable names, you can also perform mathematical operations in f-strings. You can place the mathematical expression inside the curly braces and, if you add an equal sign, you'll get the expression and its result.
```py
num_val = 42
print(f'{num_val % 2 = }') # num_val % 2 = 0
```
### Printable representation
Apart from plain string interpolation, you might want to get the printable representation of a value. This is already easy to accomplish using the `repr()` function. f-strings provide a much shorter syntax by appending a `!r` inside the curly braces.
```py
str_val = 'apples'
print(f'{str_val!r}') # 'apples'
```
### Number formatting
Additionally, f-strings can also be used for formatting - hence the **f** in the name. To add formatting to a value you can add a colon (`:`) followed by a format specifier. This can also be combined with the equals sing from before, shall you want to print the name of the variable as well.
Numbers are a great candidate for this. If, for example, you want to trim a numeric value to two digits after the decimal, you can use the `.2f` format specifier.
```py
price_val = 6.12658
print(f'{price_val:.2f}') # 6.13
```
### Date formatting
Finally, dates can also be formatted the same way as numbers, using format specifiers. As usual, `%Y` denotes the full year, `%m` is the month and `%d` is the day of the month.
```py
from datetime import datetime;
date_val = datetime.utcnow()
print(f'{date_val=:%Y-%m-%d}') # date_val=2021-07-09
```

View File

@ -0,0 +1,63 @@
---
title: Code Anatomy - Writing high performance Python code
shortTitle: Performant Python code
type: story
language: python
tags: [list,performance]
cover: walking-on-top
excerpt: Writing efficient Python code can be tricky. Read how we optimize our list snippets to increase performance using a couple of simple tricks.
dateModified: 2021-11-07T16:34:37+03:00
---
Writing short and efficient Python code is not always easy or straightforward. However, it's often that we see a piece of code and we don't realize the thought process behind the way it was written. We will be taking a look at the [difference](/python/s/difference) snippet, which returns the difference between two iterables, in order to understand its structure.
Based on the description of the snippet's functionality, we can naively write it like this:
```py
def difference(a, b):
return [item for item in a if item not in b]
```
This implementation may work well enough, but doesn't account for duplicates in `b`. This makes the code take more time than necessary in cases with many duplicates in the second list. To solve this issue, we can make use of the `set()` method, which will only keep the unique values in the list:
```py
def difference(a, b):
return [item for item in a if item not in set(b)]
```
This version, while it seems like an improvement, may actually be slower than the previous one. If you look closely, you will see that `set()` is called for every `item` in `a` causing the result of `set(b)` to be evaluated every time. Here's an example where we wrap `set()` with another method to better showcase the problem:
```py
def difference(a, b):
return [item for item in a if item not in make_set(b)]
def make_set(itr):
print('Making set...')
return set(itr)
print(difference([1, 2, 3], [1, 2, 4]))
# Making set...
# Making set...
# Making set...
# [3]
```
The solution to this issue is to call `set()` once before the list comprehension and store the result to speed up the process:
```py
def difference(a, b):
_b = set(b)
return [item for item in a if item not in _b]
```
Another option worth mentioning in terms of performance is the use of a list comprehension versus `filter()` and `list()`. Implementing the same code using the latter option would result in something like this:
```py
def difference(a, b):
_b = set(b)
return list(filter(lambda item: item not in _b, a))
```
Using `timeit` to analyze the performance of the last two code examples, it's pretty clear that using list comprehension can be up to ten times faster than the alternative. This is due to it being a native language feature that works very similar to a simple `for` loop without the overhead of the extra function calls. This explains why we prefer it, apart from readability.
This pretty much applies to most mathematical list operation snippets, such as [difference](/python/s/difference), [symmetric_difference](/python/s/symmetric-difference) and [intersection](/python/s/intersection).

View File

@ -0,0 +1,32 @@
---
title: "Tip: Set up Python 3 and pip 3 as default"
shortTitle: Python 3 and pip 3 setup
type: tip
language: python
tags: [setup]
author: chalarangelo
cover: avocado-slices
excerpt: A very common problem when working with Python is having to remember the correct version. Luckily, there's an easy fix for that.
dateModified: 2021-06-12T19:30:41+03:00
---
One of the most common headaches when working with Python is having to remember to use Python 3.x instead of Python 2.x. Luckily, it's really easy to setup Python 3 and pip 3 as the defaults. You first need to figure out where each one is installed using the `which` command:
```shell
which python3 # /usr/local/bin/python3
which pip3 # /usr/local/bin/pip3
```
Make a note of each response, so that you can add the paths as aliases to your shell environment's configuration file. Then, you can use `echo` to add a line for each one to either `.zshrc` or `.bashrc` depending on your environment:
```shell
# Linux or other bash environment
echo "alias python=/usr/local/bin/python3" >> ~/.bashrc
echo "alias pip=/usr/local/bin/pip3" >> ~/.bashrc
# Mac OS or other zsh environment
echo "alias python=/usr/local/bin/python3" >> ~/.zshrc
echo "alias pip=/usr/local/bin/pip3" >> ~/.zshrc
```
And you're all done! `python` and `pip` are both mapped to their 3.x versions,