Python3 String Rjust
## Python3 String rjust() Method
The `rjust()` method returns a new string of a specified length, where the original string is right-aligned and padded on the left with a designated character (which defaults to an ASCII space).
---
## Syntax
```python
str.rjust(width[, fillchar])
```
### Parameters
* **`width`**: An integer specifying the total length of the resulting string after padding.
* **`fillchar`** *(Optional)*: A single character used to fill the remaining space on the left. The default value is an ASCII space (`' '`).
### Return Value
* Returns a new, right-aligned string padded to the specified `width`.
* If the specified `width` is less than or equal to the length of the original string, the original string is returned unmodified.
---
## Code Examples
### Example 1: Basic Usage with Default Padding (Spaces)
By default, `rjust()` pads the string with spaces.
```python
# Original string of length 11
text = "Hello World"
# Right-align and pad to a total length of 20
result = text.rjust(20)
print(f"Original: '{text}' (Length: {len(text)})")
print(f"Padded: '{result}' (Length: {len(result)})")
```
**Output:**
```text
Original: 'Hello World' (Length: 11)
Padded: ' Hello World' (Length: 20)
```
---
### Example 2: Using a Custom Fill Character
You can specify a custom character, such as an asterisk (`*`) or a hyphen (`-`), to fill the padding space.
```python
# Original string of length 32
text = "this is string example....wow!!!"
# Right-align and pad with '*' to a total length of 50
result = text.rjust(50, '*')
print(result)
```
**Output:**
```text
******************this is string example....wow!!!
```
---
### Example 3: Handling Widths Smaller Than the String Length
If the `width` parameter is smaller than or equal to the length of the original string, Python returns the original string without truncating it.
```python
text = "Python"
# The length of "Python" is 6. Requesting a width of 4:
result = text.rjust(4, '-')
print(result)
```
**Output:**
```text
Python
```
---
## Key Considerations
1. **Single Character Constraint for `fillchar`**: The `fillchar` argument 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.rjust(10, 'ab')
```
2. **Immutability**: Like all Python string methods, `rjust()` does not modify the original string in place. It returns a brand-new string object.
3. **Complementary Methods**:
* Use `ljust()` to left-align a string with padding on the right.
* Use `center()` to center-align a string with padding on both sides.
* Use `zfill()` specifically for zero-padding numeric strings on the left.
YouTip