How to Truncate a String in Python 3 to a Max Number of Characters

To limit the length of a Python string, you can get a part of the string using bracket notation. You don't need to worry about the length of the string:

letters = 'abcdefg'
print(letters[0:10])

the result of running the above code is:

abcdefg

and no errors are thrown, even though abcdefg is only 7 characters.

If our string were longer:

letters = 'abcdefghijklmnop'
print(letters[0:10])

the result would be:

abcdefghij

which is 10 characters long. The bracket notation is [from:to], and the character at the to index is not included.

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.