Truncate StringUse string slice syntax to truncate a string. A truncated string is a substring of the first part.
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)
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.