Rename articles prefixed with python-

This commit is contained in:
Angelos Chalaris
2023-05-18 23:32:28 +03:00
parent 00f280bd16
commit a55cf45112
17 changed files with 0 additions and 0 deletions

View File

@ -0,0 +1,47 @@
---
title: "Tip: Avoid using bare except in Python"
shortTitle: Bare except best practices
type: tip
language: python
tags: [error]
cover: dark-cloud
excerpt: It's generally not a good idea to use bare `except` clause in Python, but do you know why?
dateModified: 2022-02-20T05:00:00-04:00
---
In Python, keyboard interrupts and system exits are propagated using exceptions (i.e. `KeyboardInterrupt` and `SystemExit`). As a result, a bare `except` clause is going to catch something like the user hitting <kbd>Ctrl</kbd> + <kbd>C</kbd>.
Consider the following code. If the user were to try exiting the program, the keyboard interrupt would be caught by the `except` clause. This would be undesirable, as it prevents the user from actually exiting the program until they provide valid input.
```py
while True:
try:
s = input('Input a number:')
x = int(s)
except:
print('Not a number, try again!')
```
A way to prevent this would be to use `Exception` which will ensure that the user will not be trapped. The only problem with this approach is that `Exception` is generic and will handle pretty much anything thrown at it.
```py
while True:
try:
s = input('Input a number:')
x = int(s)
except Exception:
print('Not a number, try again!')
```
The correct way to handle errors is to specify the type of error you expect. For example, in this code sample, `ValueError` would be appropriate.
```py
while True:
try:
s = input('Input a number:')
x = int(s)
except ValueError:
print('Not a number, try again!')
```
As a rule of thumb, you should only handle expected failure states using `except` with an appropriate error type. In the case of unexpected errors, it might be better to simply let the program fail naturally and exit.

View File

@ -0,0 +1,23 @@
---
title: "Tip: You should use dict.get(key) instead of dict[key]"
shortTitle: dict.get(key) vs dict[key]
type: tip
language: python
tags: [dictionary]
cover: compass-2
excerpt: Learn the difference between two common ways to access values in Python dictionaries and level up your code today.
dateModified: 2021-06-12T19:30:41+03:00
---
A common debate among Python developers seems to stem from the retrieval of dictionary values, which can be accomplished using either `dict[key]` or `dict.get(key)`.
Although you can achieve the same result using either one, `dict.get()` is usually preferred, as it accepts a second argument which acts as the default value shall the key not exist in the given dictionary. Due to this property, `dict.get()` will always return a value, whereas `dict[key]` will raise a `KeyError` if the given key is missing.
```py
a = { 'max': 200 }
b = { 'min': 100, 'max': 250 }
c = { 'min': 50 }
a['min'] + b['min'] + c['min'] # throws KeyError
a.get('min', 0) + b.get('min', 0) + c.get('min', 0) # 150
```

View File

@ -0,0 +1,25 @@
---
title: How can I check if a Python list is empty?
shortTitle: Empty list
type: question
language: python
tags: [list]
author: chalarangelo
cover: salad-2
excerpt: There's a good way to test the emptiness of a Python list and a better one. Which one are you using?
dateModified: 2023-01-15T05:00:00-04:00
---
Checking the emptiness of a Python list is rather easy using the `len()` function. Yet, there's another technique that works on all types of sequences and collections. This is based on the **truth value testing** of the sequence or collection itself.
By default, a Python object is considered truthy unless its class defines either a `__bool__()` or a `__len__()` method that returns `False` or `0` respectively. Python's built-in objects, such as tuples, lists, strings, dictioners, sets and ranges all implement a `__len__()` method. This menas that truth value testing of these objects will return `False` if they are empty, and `True` otherwise.
Based on these observations, all you need to check if a Python list is empty is to test its truth value, using the `not` operator.
```py
x = []
not x # True
y = [1, 2]
not y # False
```

View File

@ -0,0 +1,37 @@
---
title: How to correctly close files in Python
shortTitle: Closing files
type: story
language: python
tags: [file]
cover: flower-pond
excerpt: When working with files in Python, it's important to ensure that the file is closed correctly. Here are a couple of ways to do that.
dateModified: 2022-02-03T05:00:00-04:00
---
When working with files in Python, it's quite common to explicitly invoke the `close()` method after processing the file. This might work fine in a lot of cases, however it's a common pitfall for beginners and developers coming from other languages.
Take for example the following code. If an exception is thrown before calling the `close()` method, the file would remain open. In such a scenario, the code would stop executing before `close()` is called, leaving the file open after the program crashes.
```py
f = open('filename', 'w')
f.write('Hello world!')
f.close()
```
One way to mitigate this problem is to encapsulate the `write()` call in a `try` statement. This way, you can handle any exceptions and you can use `finally` to ensure the file gets closed.
```py
f = open('filename', 'w')
try:
f.write('Hello world!')
finally:
f.close()
```
Another option offered by Python is to use a `with` statement which will ensure the file is closed when the code that uses it finishes running. This holds true even if an exception is thrown.
```py
with open('filename', 'w') as f:
f.write('Hello world!')
```

View File

@ -0,0 +1,32 @@
---
title: "Tip: 2 ways to format a string in Python"
shortTitle: String formatting
type: tip
language: python
tags: [string]
cover: feathers
excerpt: Learn two ways to format a string in Python with this quick tip.
dateModified: 2021-06-12T19:30:41+03:00
---
### f-string
[Formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html?highlight=lexical%20analysis#formatted-string-literals), commonly known as f-strings, are strings prefixed with `'f`' or `'F'`. These strings can contain replacement fields, enclosed in curly braces (`{}`).
```py
name = 'John'
age = 32
print(f'{name} is {age} years old') # 'John is 32 years old'
```
### str.format()
The [`str.format()`](https://docs.python.org/3/library/stdtypes.html?highlight=str%20format#str.format) method works very much alike f-strings, the main difference being that replacement fields are supplied as arguments instead of as part of the string.
```py
name = 'John'
age = 32
print('{0} is {1} years old'.format(name, age)) # 'John is 32 years old'
```

View File

@ -0,0 +1,45 @@
---
title: What is the difference between Python's equality operators?
shortTitle: Python equality operators
type: question
language: python
tags: [type,comparison]
cover: umbrellas
excerpt: Python provides two distinct comparison operators for different task. Stop mixing them up using this quick guide.
dateModified: 2021-06-12T19:30:41+03:00
---
Python provides two very similar equality operators used for comparisons:
- The double equals (`==`), also known as the equality operator
- The `is` keyword, also known as the identity operator
Although similar to one another, the double equals (`==`) and the `is` keyword are used for different comparison purposes and yield different results.
The main difference between the two is that the `is` keyword checks for reference equality while the double equals (`==`) operator checks for value equality. In other words, `is` will return `True` if two variables both refer to the same object in memory (aka. identity), whereas the double equals operator will evaluate to `True` if the two objects have the same value.
Here are some examples to clear up any confusion:
```py
a = [1, 2, 3]
b = a
c = [x for x in a]
print([
a == b, # True
a is b, # True
a == c, # True
a is c # False
])
x = 'hi'
y = x
z = 'HI'.lower()
print([
x == y, # True
x is y, # True
x == z, # True
x is z # False
])
```

View File

@ -0,0 +1,31 @@
---
title: What is the difference between lists and tuples in Python?
shortTitle: Lists vs Tuples
type: question
language: python
tags: [list]
author: chalarangelo
cover: red-mountain
excerpt: Learn how Python's lists and tuples are different and level up your code today.
dateModified: 2021-06-12T19:30:41+03:00
---
Python's lists and tuples may seem pretty similar in syntax and function, however they have some major differences the most important of which is the fact that lists are mutable and tuples aren't. Here's a quick breakdown:
### Lists
- Syntax: `[1, 2, 3]`
- Contained elements are mutable (can be changed after creation)
- Lists have a variable length
- A list takes up more memory than a tuple
### Tuples
- Syntax: `(1, 2, 3)`
- Contained elements are immutable (cannot be changed after creation)
- Tuples have a fixed length
- A tuple takes up less memory than a list
### When to use each one
Lists provide a more accessible API and should be used whenever similar types of objects need to be stored and are expected to change over the course of the application's execution. On the other hand, tuples should be used for immutable data, behaving more like constants than variables.

View File

@ -0,0 +1,34 @@
---
title: How do I convert a string to lowercase in Python?
shortTitle: Lowercase string
type: question
language: python
tags: [string]
cover: type-stamps
excerpt: Learn of the two different ways to convert strings to lowercase in Python and understand when you should use each one with this quick guide.
dateModified: 2021-06-12T19:30:41+03:00
---
### str.lower()
Python's standard method for converting a string to lowercase is `str.lower()` and is compatible with both Python 2 and Python 3. While this is the standard way for most cases, there are certain cases where this method might not be the most appropriate, especially if you are working with Unicode strings.
```py
'Hello'.lower() # 'hello'
'Straße'.lower() # 'straße'
'Straße'.upper().lower() # 'strasse'
# Example of incorrect result when used for unicode case-insensitive matching
'Straße'.upper().lower() == 'Straße'.lower() # False ('strasse' != 'straße')
```
### str.casefold()
Python 3 introduced `str.casefold()`, which is very similar to `str.lower()`, but more aggressive as it is intended to remove all case distinctions in Unicode strings. It implements the casefolding algorithm as described in [section 3.13 of the Unicode Standard](https://www.unicode.org/versions/Unicode9.0.0/ch03.pdf).
```py
'Hello'.casefold() # 'hello'
'Straße'.casefold() # 'strasse'
'Straße'.upper().casefold() # 'strasse'
# Returns the correct result when used for unicode case-insensitive matching
'Straße'.upper().casefold() == 'Straße'.casefold() # True
```

View File

@ -0,0 +1,36 @@
---
title: "Tip: Watch out for mutable default arguments in Python"
shortTitle: Mutable default arguments
type: tip
language: python
tags: [function]
cover: goat-wooden-cottage
excerpt: Mutable default arguments can trip up Python beginners and veterans alike. Here's a quick workaround to deal with them.
dateModified: 2022-02-27T05:00:00-04:00
---
Default arguments in Python are evaluated only once. The evaluation happens when the function is defined, instead of every time the function is called. This can inadvertently create **hidden shared state**, if you use a mutable default argument and mutate it at some point. This means that the mutated argument is now the default for all future calls to the function as well.
Take the following code as an example. Every call to the function shares the same list. So, the second time it's called, the function doesn't start out with an empty list. Instead, the default argument is the list containing the value from the previous call.
```py
def append(n, l = []):
l.append(n)
return l
append(0) # [0]
append(1) # [0, 1]
```
If you absolutely need to use a mutable object as the default value in a function, you can set the default value of the argument to `None` instead. Then, checking in the function body if it is `None`, you can set it to the mutable value you want without side effects.
```py
def append(n, l = None):
if l is None:
l = []
l.append(n)
return l
append(0) # [0]
append(1) # [1]
```

View File

@ -0,0 +1,39 @@
---
title: What are named tuples in Python?
shortTitle: Named Tuples
type: question
language: python
tags: [list,dictionary]
cover: mask-quiet
excerpt: Understand Python's named tuples and start using them in your projects today.
dateModified: 2021-06-12T19:30:41+03:00
---
Python's named tuples are a very simple yet interesting feature that can make a developer's life easier. They are part of the `collections` module and act very similar to regular tuples, the main difference being that values stored in a named tuple can be accessed using field names instead of indexes.
For example, a point in the two-dimensional plane can be represented using two coordinates. In a regular tuple, these values would be accessed by index (`[0]` and `[1]`), but if we define a named tuple, `Point`, we can access them using `x` and `y` instead (although we can still use indexes, too, if we want):
```py
from collections import namedtuple
# Regular tuple
p = (2, 4) # p[0] = 2, p[1] = 4
# Named tuple
Point = namedtuple('Point', 'x y')
q = Point(3, 5) # q.x = 3, q.y = 5
```
Apart from the increased readability of your code, named tuples provide a few other quality of life improvements. First and foremost, they allow for default values to be specified via the `defaults` iterable argument. Secondly, they have the ability to automatically rename duplicate or invalid fields via the `rename` boolean argument. And, finally, they even provide a convenient option to specify field names as a list or comma/space-separated string.
```py
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y', 'z'], defaults = [1]);
a = Point(1, 1, 0); # a.x = 1, a.y = 1, a.z = 0
# Default value used for `z`
b = Point(2, 2); # b.x = 2, b.y = 2, b.z = 1 (default)
```
_Where's the catch?_ you might ask. Well, it seems like there's none! The obvious parallel to dictionaries in terms of syntax doesn't seem to go any further, as named tuple instances do not have per-instance dictionaries, meaning they require as much memory as regular tuples.

View File

@ -0,0 +1,70 @@
---
title: Understanding Python's slice assignment
shortTitle: Python slice assignment
type: story
language: python
tags: [list]
cover: sliced-fruits
excerpt: Learn everything you need to know about Python's slice assignment with this handy guide.
dateModified: 2021-06-12T19:30:41+03:00
---
#### Python slice notation
- [Understanding Python's slice notation](/blog/s/python-slice-notation)
- Understanding Python's slice assignment (this blog post)
### Basic syntax
In order to understand Python's slice assignment, you should at least have a decent grasp of how slicing works. Here's a quick recap:
```py
[start_at:stop_before:step]
```
Where `start_at` is the index of the first item to be returned (included), `stop_before` is the index of the element before which to stop (not included) and `step` is the stride between any two items.
Slice assignment has the same syntax as slicing a list with the only exception that it's used on the left-hand side of an expression instead of the right-hand side. Since slicing returns a list, slice assignment requires a list (or other iterable). And, as the name implies, the right-hand side should be the value to assign to the slice on the left-hand side of the expression. For example:
```py
nums = [1, 2, 3, 4, 5]
nums[:1] = [6] # [6, 2, 3, 4, 5] (replace elements 0 through 1)
nums[1:3] = [7, 8] # [6, 7, 8, 4, 5] (replace elements 1 through 3)
nums[-2:] = [9, 0] # [6, 7, 8, 9, 0] (replace the last 2 elements)
```
### Changing length
The part of the list returned by the slice on the left-hand side of the expression is the part of the list that's going to be changed by slice assignment. This means that you can use slice assignment to replace part of the list with a different list whose length is also different from the returned slice. For example:
```py
nums = [1, 2, 3, 4, 5]
nums[1:4] = [6, 7] # [1, 6, 7, 5] (replace 3 elements with 2)
nums[-1:] = [8, 9, 0] # [1, 6, 7, 8, 9, 0] (replace 1 element with 3)
nums[:1] = [] # [6, 7, 8, 9, 0] (replace 1 element with 0)
```
If you take empty slices into account, you can also insert elements into a list without replacing anything in it. For example:
```py
nums = [1, 2, 3, 4, 5]
nums[2:2] = [6, 7] # [1, 2, 6, 7, 3, 4, 5] (insert 2 elements)
nums[7:] = [8, 9] # [1, 2, 6, 7, 3, 4, 5, 8, 9] (append 2 elements)
nums[:0] = [0] # [0, 1, 2, 6, 7, 3, 4, 5, 8, 9] (prepend 1 element)
nums[:] = [ 4, 2] # [4, 2] (replace whole list with a new one)
```
### Using steps
Last but not least, `step` is also applicable in slice assignment and you can use it to replace elements that match the iteration after each stride. The only difference is that if `step` is not `1`, the inserted list must have the exact same length as that of the returned list slice. For example:
```py
nums = [1, 2, 3, 4, 5]
nums[2:5:2] = [6, 7] # [1, 2, 6, 4, 7] (replace every 2nd element, 2 through 5)
nums[2:5:2] = [6, 7, 8] # Throws a ValueError (can't replace 2 elements with 3)
nums[1::-1] = [9, 0] # [0, 9, 6, 4, 7] (reverse replace, 1 through start)
```

View File

@ -0,0 +1,78 @@
---
title: Understanding Python's slice notation
shortTitle: Python slice notation
type: story
language: python
tags: [list]
cover: sliced-fruits
excerpt: Learn everything you need to know about Python's slice notation with this handy guide.
dateModified: 2021-06-12T19:30:41+03:00
---
#### Python slice notation
- Understanding Python's slice notation (this blog post)
- [Understanding Python's slice assignment](/blog/s/python-slice-assignment)
### Basic syntax
Python's slice notation is used to return a list or a portion of a list. The basic syntax is as follows:
```py
[start_at:stop_before:step]
```
Where `start_at` is the index of the first item to be returned (included), `stop_before` is the index of the element before which to stop (not included) and `step` is the stride between any two items.
All three of the arguments are optional, meaning you can omit any of them. For example:
```py
nums = [1, 2, 3, 4, 5]
nums[1:4] # [2, 3, 4] (start at 0, stop before 4)
nums[2:] # [3, 4, 5] (start at 0, stop at end of list)
nums[:3] # [1, 2, 3] (start at 0, stop before 3)
nums[1:4:2] # [2, 4] (start at 1, stop before 4, every 2nd element)
nums[2::2] # [3, 5] (start at 2, stop at end of list, every 2nd element)
nums[:3:2] # [1, 3] (start at 0, stop before 3, every 2nd element)
nums[::2] # [1, 3, 5] (start at 0, stop at end of list, every 2nd element)
nums[::] # [1, 2, 3, 4, 5] (start at 0, stop at end of list)
```
As you can probably tell from the examples above, the default values are `start_at = 0`, `stop_before = len(nums)`, `step = 1`.
> An idiomatic way to shallow clone a list would be using `[:]` (e.g. `nums_clone = nums[:]`).
### Negative values
All three of the arguments also accept negative values. For `start_at` and `stop_before`, a negative value means counting from the end of the list instead of counting from the start. For example `-1` would represent the last element, `-2` the second last element etc. For example:
```py
nums = [1, 2, 3, 4, 5]
nums[1:-2] # [2, 3] (start at 1, stop before 2nd to last)
nums[-3:-1] # [3, 4] (start at 3rd to last, stop before last)
```
A negative `step` means that the list is sliced in reverse (from end to start). This also means that `start_at` should be greater than `stop_before` and that `stop_before` in the context of a reverse stride is more like `stop_after` if you are looking at the list non-reversed. For example:
```py
nums = [1, 2, 3, 4, 5]
nums[::-1] # [5, 4, 3, 2, 1] (reversed)
nums[4:1:-1] # [5, 4, 3] (reversed, start at 4, stop after 1)
nums[-1:1:-2] # [5, 3] (reversed, start at last, stop after 1, every 2nd)
```
### Empty slices
Bear in mind that slice notation is very forgiving, so you'll get an empty list if the arguments' values are out of the list's range. For example:
```py
nums = [1, 2, 3, 4, 5]
nums[6:8] # []
nums[:-10] # []
```
[Continue on Understanding Python's slice assignment](/blog/s/python-slice-assignment)

View File

@ -0,0 +1,37 @@
---
title: "Tip: Sort Python dictionary list using a tuple key"
shortTitle: Sort dictionary list using a tuple key
type: tip
language: python
tags: [list,dictionary]
author: chalarangelo
cover: matrix-flow
excerpt: Learn how to sort a Python dictionary list using a tuple key.
dateModified: 2023-01-04T05:00:00-04:00
---
Sorting a list of dictionaries in Python can seem intimidating at first. This is especially true if you want to **sort using multiple keys**. Luckily, the `sorted()` function can be used to sort a list of dictionaries using a tuple `key`. Simply return a **tuple** with the order of keys you want to sort by and the `sorted()` function will do the rest.
```py
friends = [
{"name": "John", "surname": "Doe", "age": 26},
{"name": "Jane", "surname": "Doe", "age": 28},
{"name": "Adam", "surname": "Smith", "age": 30},
{"name": "Michael", "surname": "Jones", "age": 28}
]
print(
sorted(
friends,
key=lambda friend:
(friend["age"], friend["surname"], friend["name"])
)
)
# PRINTS:
# [
# {'name': 'John', 'surname': 'Doe', 'age': 26},
# {'name': 'Jane', 'surname': 'Doe', 'age': 28},
# {'name': 'Michael', 'surname': 'Jones', 'age': 28},
# {'name': 'Adam', 'surname': 'Smith', 'age': 30}
# ]
```

View File

@ -0,0 +1,32 @@
---
title: What is the difference between list.sort() and sorted() in Python?
shortTitle: List.sort vs sorted
type: question
language: python
tags: [list]
cover: duck-plants
excerpt: Learn the difference between Python's built-in list sorting methods and when one is preferred over the other.
dateModified: 2021-06-12T19:30:41+03:00
---
Python provides two ways to sort a list, the built-in list method `list.sort()` and the built-in function `sorted()`. Although both will sort the elements of a list, if used incorrectly they can produce unexpected or undesired results.
### Differences and similarities
The primary difference between the two is that `list.sort()` will sort the list in-place, mutating its indexes and returning `None`, whereas `sorted()` will return a new sorted list leaving the original list unchanged. Another difference is that `sorted()` accepts any iterable while `list.sort()` is a method of the `list` class and can only be used with lists.
```py
nums = [2, 3, 1, 5, 6, 4, 0]
print(sorted(nums)) # [0, 1, 2, 3, 4, 5, 6]
print(nums) # [2, 3, 1, 5, 6, 4, 0]
print(nums.sort()) # None
print(nums) # [0, 1, 2, 3, 4, 5, 6]
```
Both `list.sort()` and `sorted()` have the same `key` and `reverse` optional arguments and can be called on each list element prior to making comparisons.
### When to use each one
`list.sort()` should be used whenever mutating the list is intended and retrieving the original order of the elements is not desired. On the other hand, `sorted()` should be used when the object to be sorted is an iterable (e.g. list, tuple, dictionary, string) and the desired outcome is a sorted list containing all elements.

View File

@ -0,0 +1,35 @@
---
title: How can I check if a string is empty in Python?
shortTitle: String is empty
type: question
language: python
tags: [string]
author: chalarangelo
cover: tea-laptop-table
excerpt: Here are two quick and elegant ways to check if a string is empty in Python.
dateModified: 2022-08-05T05:00:00-04:00
---
When working with Python strings, a pretty common question is how does one check if a string is empty. There's a straightforward answer to this that takes advantage of the truth value of strings.
In Python, any object can be tested for truth value, including strings. In this context, **strings are considered truthy if they are non-empty**, meaning they contain at least one character. Thus, simply using the `not` operator, you can check if a string is empty.
```py
empty_string = ''
non_empty_string = 'Hello'
not empty_string # True
not non_empty_string # False
```
While this method works in most cases, you may also need to check if the actual value is a string. In this case, you can compare your string to the empty string using the `==` operator.
```py
empty_string = ''
non_empty_string = 'Hello'
non_string = 0
empty_string == '' # True
non_empty_string == '' # False
non_string == '' # False
```

View File

@ -0,0 +1,58 @@
---
title: 3 ways to swap two variables in Python
shortTitle: Variable swapping
type: story
language: python
tags: [variables]
cover: leaves-read
excerpt: Learn 3 easy ways to swap the values of two variables in Python.
dateModified: 2021-11-07T16:34:37+03:00
---
### Using a temporary variable
The simplest way to swap the values of two variables is using a `temp` variable. The `temp` variables is used to store the value of the fist variable (`temp = a`). This allows you to swap the value of the two variables (`a = b`) and then assign the value of `temp` to the second variable.
```py
a = 11
b = 7
temp = a
a = b
b = temp
print(a) # 7
print(b) # 11
```
### Without a temporary variable (Tuple swap)
Another way to swap the values of two variables, without using a temporary variable, is to use **tuple packing** and **sequence unpacking**. Tuples can be constructed in a number of ways, one of which is by separating tuple items using commas. Moreover, Python evaluates the right-hand side of an assignment before its left-hand side. So, by separating the variables with commas on the right side of the statement the variables are packed into a tuple and unpacked by placing the same number of comma-separated target variables on the left side.
This method of variable swapping and permutation can be used for more than two variables as long as the same number of variables are on both sides of the statement.
```py
a = 11
b = 7
a, b = b, a
print(a) # 7
print(b) # 11
```
### Using arithmetic operators (for numbers only)
If the two variables are numbers, their values can be swapped using arithmetic operators such as addition and subtraction (`+`, `-`) or multiplication and division (`*`, `/`). This swapping method is based on calculating the sum of the two numbers and then swapping them using the sum and the difference from the sum.
```py
a = 11
b = 7
a = a + b # a = 18, b = 7
b = a - b # a = 18, b = 11
a = a - b # a = 7, b = 11
print(a) # 7
print(b) # 11
```

View File

@ -0,0 +1,36 @@
---
title: How do I trim whitespace from a string in Python?
shortTitle: Trim whitespace
type: question
language: python
tags: [string]
cover: organizer
excerpt: Oftentimes you might need to trim whitespace from a string in Python. Learn of three different way to do this in this short guide.
dateModified: 2021-12-13T05:00:00-04:00
---
When working with Python strings, a pretty common question is how to trim whitespace from a string. Whitespace characters are the space (` `), tab (`\t`), newline (`\n`), and carriage return characters (`\r`). Here are 3 different methods to trim whitespace from a string in Python.
### Remove leading and trailing whitespace characters
Use the `str.strip()` method to remove whitespace characters from both the beginning and end of a string.
```py
' Hello '.strip() # 'Hello'
```
### Remove leading whitespace characters
Leading whitespace characters are the whitespace characters at the start of a string. To remove them, use the `str.lstrip()` method.
```py
' Hello '.lstrip() # 'Hello '
```
### Remove trailing whitespace characters
Trailing whitespace characters are the whitespace characters at the end of a string. To remove them, use the `str.rstrip()` method.
```py
' Hello '.rstrip() # ' Hello'
```