Last updated: Apr 9, 2024
Reading timeยท5 min
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.
my_str = 'bobbyhadz.com' result = my_str[:5] print(result) # ๐๏ธ bobby
We used string slicing to truncate a string.
The syntax for string slicing is my_str[start:stop:step]
.
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.
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.
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.
If you have to do this often, define a reusable function.
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...
The function takes a string, the desired length and optionally a suffix as parameters and truncates the given string to the specified length.
Alternatively, you can use a formatted string literal.
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...
f
.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.
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.
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.
my_str = 'bobby hadz com' 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.
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:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At 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
.
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.
You can also use the textwrap.shorten()
method to truncate a string.
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 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.
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:
width
.You can also use the str.format()
method to truncate a string.
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 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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: