Format a string limiting its length in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Format a string limiting its length in Python #

Use a formatted string literal to format a string and limit its length, e.g. result = f'{my_str:5.5}'. You can use expressions in f-strings to limit the string's length to a given number of characters.

main.py
my_str = 'bobbyhadz' # ✅ limit string length to 5 characters result = f'{my_str:5.5}' print(result) # 👉️ 'bobby' # 👇️ limit string length removing excess trailing characters result = my_str[:5] print(result) # 👉️ 'bobby' # 👇️ limit string length removing excess leading characters result = my_str[-5:] print(result) # 👉️ 'yhadz'

The first example uses a formatted string literal to limit a string's length.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

main.py
my_str = 'bobbyhadz' result = f'{my_str:5.5}' print(result) # 👉️ 'bobby'

The digit right after the colon is the width to format the string to.

The string gets left-padded with spaces if necessary.

main.py
my_str = 'b' result = f'{my_str:5.5}' print(repr(result)) # 👉️ 'b '

If you don't want to pad the string with spaces if it is shorter, remove the digit after the colon.

main.py
my_str = 'bobbyhadz' result = f'{my_str:.5}' print(result) # 👉️ bobby

The digit after the period is the maximum size of the string.

The example formats the string to a maximum of 5 characters.

Alternatively, you can use string slicing.

main.py
my_str = 'bobbyhadz' # 👇️ limit string length removing excess trailing characters result = my_str[:5] print(result) # 👉️ 'bobby' # 👇️ limit string length removing excess leading characters result = my_str[-5:] print(result) # 👉️ 'yhadz'

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

If you need to only get the first N characters of a string, specify a stop index of N.

main.py
my_str = 'bobbyhadz' result = my_str[:5] print(result) # 👉️ 'bobby'

The stop index is exclusive (up to, but not including), so the slice only consists of the first 5 characters of the string.

If you need to get the last N characters of a string, specify a start index of -N.

main.py
my_str = 'bobbyhadz' result = my_str[-5:] print(result) # 👉️ 'yhadz'
Negative indices can be used to count backwards, e.g. my_str[-3:] returns the last 3 characters in the string.

If you need to pad the string with spaces to a fixed length, use the str.ljust and str.rjust() methods.

main.py
my_str = 'b' result = my_str[-3:].ljust(3) print(repr(result)) # 👉️ 'b ' result = my_str[-3:].rjust(3) print(repr(result)) # 👉️ ' b'

The str.ljust method pads the end of the string to the specified width with the provided fill character.

If no fill character is specified, the string gets padded with spaces.

The str.rjust method pads the beginning of the string to the specified width with the provided fill character.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.