Consider a Python string that contains the letters "abcdef." But we only want the "abc" part. We need to truncate the string
—slice syntax can be used.
Substring
notesWith a first index of 0, we take a substring of the string
from its start. We can omit the zero—Python assumes a zero in this case.
Here we have a string
with three words in it. We first want to truncate the string
to three characters. We use "0:3" to do this.
string
to 3 and to 7 characters. If we use an out of range number like 100 the entire string
is returned.value = "one two three" # Truncate the string to 3 characters. first = value[0:3] print(first + ".") # Truncate the string to 7 characters. second = value[0:7] print(second + ".")one. one two.
As a Python developer, we grow tired of typing characters. The leading zero can be omitted for a truncation. Python assumes the "0:3" in this program.
letters = "abcdef" # Omit the first 0 in the slice syntax. # ... This truncates the string. first_part = letters[:3] print(first_part)abc
For negative values, our truncation method will truncate from the end of the string
. This is the same as string
slice syntax in Python.
In some languages like Java we will get exceptions with invalid indexes and lengths. This is not the case with Python—invalid indexes are reduces to be valid.
String
truncation requires no truncate()
method call. A truncate()
call exists but it is for file handling, not strings. We use string
slices to truncate strings.