Truncate. 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 notes. With 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.
Truncation example. 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.
Detail We truncate the 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.
Omit zero. 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
Some notes. For negative values, our truncation method will truncate from the end of the string. This is the same as string slice syntax in Python.
No errors. 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.
A review. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.