How to truncate a String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Truncate a string in Python
  2. Truncate a string with an ellipsis in Python
  3. Truncate a string using a formatted string literal
  4. Truncate a string using str.rsplit()
  5. Truncate a string using textwrap.shorten()
  6. Truncate a string using str.format()

# 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' result = my_str[:5] print(result) # ๐Ÿ‘‰๏ธ bobby

truncate string in python

The code for this article is available on GitHub

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.

# Truncate a string with an ellipsis in Python

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...

truncate string with an ellipsis

The code for this article is available on GitHub

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

# Creating a reusable function

If you have to do this often, define a reusable function.

main.py
def truncate_string(string, length, suffix='...'): return string[:length] + suffix print(truncate_string('bobbyhadz.com', 3)) # bob... print(truncate_string('bobbyhadz.com', 5)) # bobby... print(truncate_string('bobbyhadz.com', 7)) # bobbyha...

creating reusable function

The function takes a string, the desired length and optionally a suffix as parameters and truncates the given string to the specified length.

# Truncate a string using a formatted string literal

Alternatively, you can use a formatted string literal.

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...

truncate string using formatted string literal

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...

# Truncate a string using str.rsplit()

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

main.py
my_str = 'bobby hadz com' new_str = my_str.rsplit(' ', 1)[0] print(new_str) # ๐Ÿ‘‰๏ธ 'bobby hadz'

truncate string using str rsplit

The code for this article is available on GitHub

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.

# Truncate a string using textwrap.shorten()

You can also use the textwrap.shorten() method to truncate a string.

main.py
import textwrap a_string = 'bobby hadz com one two three' new_string = textwrap.shorten(a_string, width=8, placeholder='') print(new_string) # ๐Ÿ‘‰๏ธ bobby new_string = textwrap.shorten(a_string, width=8, placeholder='...') print(new_string) # ๐Ÿ‘‰๏ธ bobby... new_string = textwrap.shorten(a_string, width=15, placeholder='...') print(new_string) # ๐Ÿ‘‰๏ธ bobby hadz...
The code for this article is available on GitHub

The textwrap.shorten() method takes a string, the max width of the string and a placeholder as parameter and truncates the string.

The method collapses and truncates the string to fit in the given width.

Note that the placeholder is included in the width of the string.

main.py
import textwrap a_string = 'bobby hadz com one two three' new_string = textwrap.shorten(a_string, width=5, placeholder='...') print(new_string) # ๐Ÿ‘‰๏ธ ...

The first word + the placeholder exceeds the specified max width of 5, so only the placeholder is returned.

The textwrap.shorten() method:

  1. Collapses the whitespace (replaces multiple, consecutive spaces with a single space).
  2. If the result fits in the specified width, it is returned.
  3. Otherwise, enough words are dropped from the end of the string so that the remaining words plus the placeholder fit within the specified width.

# Truncate a string using str.format()

You can also use the str.format() method to truncate a string.

main.py
a_string = 'bobby hadz com one two three' new_str = '{:.5}'.format(a_string) print(new_str) # ๐Ÿ‘‰๏ธ bobby new_str = '{:.7}'.format(a_string) print(new_str) # ๐Ÿ‘‰๏ธ bobby h new_str = '{:.3}'.format(a_string) print(new_str) # ๐Ÿ‘‰๏ธ bob
The code for this article is available on GitHub

The digit after the period is used to specify how many characters are going to be used from the string.

The str.format() method performs string formatting operations.

main.py
first = 'bobby' last = 'hadz' result = "Name: {} {}".format(first, last) print(result) # ๐Ÿ‘‰๏ธ "Name: bobby hadz"

The string the method is called on can contain replacement fields specified using curly braces {}.

You can use the ternary operator if you need to add an ellipsis if the string has a length of more than N.

main.py
a_string = 'bobby hadz com one two three' new_str = '{:.5}'.format(a_string) + "..." if len(a_string) > 5 else "" print(new_str) # ๐Ÿ‘‰๏ธ bobby...

The string in the example has more than 5 characters, so the if statement runs and an ellipsis is added at the end.

Want to learn more about truncating strings in Python? Check out these resources: Get the first N characters of a String in Python,Remove the last N characters from a String in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev