Python Truncate StringUse string slice syntax to truncate a string. A truncated string is a substring of the first part.
A string contains the letters "abcdef." But we only want the "abc" part. We need to truncate the string—slice syntax can be used.StringsSlice
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.
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.
Program: 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.
Python program that truncates string
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 + ".")
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.
Python program that uses short truncation syntax
letters = "abcdef"
# Omit the first 0 in the slice syntax.
# ... This truncates the string.
first_part = letters[:3]
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.