user
How to truncate string in Python?
alphonsio

To slice a string, simply use s[start:end]. It returns the string from the character at position start (included) to the character at position end (excluded):

original_string = "Hello, world!"
original_string[3:9] # 'lo, wo'
original_string[0:9] # 'Hello, wo'
original_string[0:13] # 'Hello, world!'

Truncating a string in Python may also mean limiting the string to a maximum number of characters and typically includes handling whether to append some indication (like ellipsis ...) that the string was shortened. Below are some methods to truncate a string in Python:

Method 1: Slicing
The simplest way to truncate a string is by using slicing. You specify the maximum length max_length and cut the string if it exceeds that length.

def truncate_string(s, max_length):
    if len(s) > max_length:
        return s[:max_length]
    return s

# Example usage
original_string = "Hello, world!"
truncated = truncate_string(original_string, 5)
print(truncated)  # Output: Hello

Method 2: Slicing with Ellipsis
If you need to show that a string has been truncated, you might want to add "..." or another indicator at the end of the string. This method involves adjusting the maximum length to accommodate the ellipsis.

def truncate_string(s, max_length):
    if len(s) > max_length:
        return s[:max_length - 3] + "..."
    return s

# Example usage
original_string = "Hello, world!"
truncated = truncate_string(original_string, 8)
print(truncated)  # Output: Hello...

Method 3: Conditional Expression
Using a conditional expression (ternary operator) can make the code more compact. It's the same as Method 1 but written more succinctly.

def truncate_string(s, max_length):
    return s if len(s) <= max_length else s[:max_length]

original_string = "Hello, world!"
truncated = truncate_string(original_string, 5)
print(truncated)  # Output: Hello

Method 4: Function with Parameter for Ellipsis
A more flexible function where you can choose whether to add ellipsis or not.

def truncate_string(s, max_length, add_ellipsis=False):
    if len(s) > max_length:
        if add_ellipsis and max_length > 3:
            return s[:max_length - 3] + "..."
        else:
            return s[:max_length]
    return s

# Example usage
original_string = "Hello, world!"
truncated = truncate_string(original_string, 10, add_ellipsis=True)
print(truncated)  # Output: Hello, w...

In each of these methods, you can further enhance or modify the truncation logic based on more complex rules or conditions, depending on how you want to handle edge cases or specific requirements (like not breaking words, etc.). These examples provide a starting point for basic string truncation scenarios.