YouTip LogoYouTip

Att String Ljust

## Python String ljust() Method The `ljust()` method returns a new string of a specified length, with the original string left-aligned and padded on the right with a designated character (which defaults to a space). If the specified width is less than or equal to the length of the original string, the original string is returned unmodified. --- ## Syntax The syntax for the `ljust()` method is as follows: ```python str.ljust(width[, fillchar]) ``` ### Parameters * **`width`** (Required): An integer specifying the total length of the resulting string after padding. * **`fillchar`** (Optional): A single character used to fill the remaining space. The default value is an ASCII space (`' '`). ### Return Value * Returns a new string padded to the specified `width` with the original string left-aligned. * If `width` is less than or equal to the length of the original string, it returns the original string without any modifications. --- ## Code Examples ### Example 1: Basic Usage with Default Padding (Spaces) By default, `ljust()` pads the string with spaces. ```python # Define the original string text = "Hello" # Left-align the string with a total width of 10 result = text.ljust(10) print(f"'{result}'") ``` **Output:** ```text 'Hello ' ``` --- ### Example 2: Custom Padding Character You can specify a custom character, such as `'0'` or `'-'`, to fill the empty space. ```python # Define the original string text = "this is string example....wow!!!" # Left-align the string with a total width of 50, padding with '0' result = text.ljust(50, '0') print(result) ``` **Output:** ```text this is string example....wow!!!000000000000000000 ``` --- ### Example 3: Width Less Than String Length If the specified `width` is smaller than the length of the original string, the string is returned as-is. ```python text = "Python" # The length of "Python" is 6. Specifying a width of 4 will not truncate it. result = text.ljust(4, '*') print(result) ``` **Output:** ```text Python ``` --- ## Considerations 1. **Single Character Constraint for `fillchar`**: The `fillchar` parameter must be exactly one character long. Passing an empty string or a string with multiple characters will raise a `TypeError`. ```python text = "Python" # This will raise: TypeError: The fill character must be exactly one character long text.ljust(10, 'ab') ``` 2. **Immutability**: Like all string methods in Python, `ljust()` does not modify the original string. It returns a completely new string object. 3. **Unicode Support**: The `fillchar` can be a Unicode character, which is useful for formatting non-ASCII text or adding visual dividers.
← Att String LowerAtt String Len β†’