How to truncate a string in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Truncate a string in Python #

Use string slicing to truncate a string, e.g. result = my_str[:5]. The slice returns the first N characters of the string. Ellipsis can be added to the end of the substring if the string is longer than the slice.

main.py
my_str = 'bobbyhadz.com' # ✅ truncate string to length of 5 characters result = my_str[:5] print(result) # 👉️ bobby # ✅ truncate string to length of 5 characters with ellipsis result = my_str[:5] + '...' if len(my_str) > 5 else my_str print(result) # 👉️ bobby...

We used string slicing to truncate a string.

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.

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

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

The example returns a substring containing the first 5 characters of the string.

You can use the ternary operator to add an ellipsis if the string is longer than the slice.

main.py
my_str = 'bobbyhadz.com' result = my_str[:5] + '...' if len(my_str) > 5 else my_str print(result) # 👉️ bobby...

The expression to the left of the if statement is returned if the condition is met, otherwise the string gets returned as is.

Alternatively, you can use a formatted string literal.

Truncate a string using a formatted string literal #

Use a formatted string literal to truncate a string, e.g. result = f'{my_str:.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.com' result = f'{my_str:.5}' print(result) # 👉️ bobby result = f'{my_str:.5}{"..." if len(my_str) > 5 else ""}' print(result) # 👉️ bobby...
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.com' 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.

You can use the ternary operator to add an ellipsis if the string is longer than the slice.

main.py
my_str = 'bobbyhadz.com' result = f'{my_str:.5}{"..." if len(my_str) > 5 else ""}' print(result) # 👉️ bobby...

If you need to remove the last word from a string, use the str.rsplit() method.

main.py
my_str = 'bobby hadz com' # ✅ Remove last word from string (using str.rsplit()) new_str = my_str.rsplit(' ', 1)[0] print(new_str) # 👉️ 'bobby hadz'

The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.

main.py
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # 👉️ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # 👉️ ['bobby hadz', 'com']

The method takes the following 2 arguments:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done, the rightmost ones (optional)

If you need to remove the last 2 words from a string, set the maxsplit argument to 2 and access the list item at index 0.

main.py
my_str = 'bobby hadz com' # 👇️ remove last word from string result = my_str.rsplit(' ', 1)[0] print(result) # 👉️ bobby hadz # 👇️ remove last 2 words from string result = my_str.rsplit(' ', 2)[0] print(result) # 👉️ bobby

The maxsplit argument can be set to split the string at most N times from the right.

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.