YouTip LogoYouTip

Att String Zfill

## Python String zfill() Method The `zfill()` method is a built-in Python string method that returns a copy of the string left-padded with `'0'` digits to reach a specified width. The original string is right-aligned. This method is particularly useful for formatting numbers, file names, or database IDs where consistent string lengths and leading zeros are required. --- ## Syntax The syntax for the `zfill()` method is as follows: ```python str.zfill(width) ``` ### Parameters * **`width`** *(required)*: An integer specifying the desired length of the resulting string. * If the specified `width` is less than or equal to the length of the original string, no padding is added, and the original string is returned as-is. ### Return Value * Returns a new string padded with leading zeros to meet the specified `width`. --- ## Code Examples ### Example 1: Basic Usage The following example demonstrates how to pad a standard string to different widths: ```python # Define a sample string text = "this is string example....wow!!!" # Pad the string to a total width of 40 characters print(text.zfill(40)) # Pad the string to a total width of 50 characters print(text.zfill(50)) ``` **Output:** ```text 00000000this is string example....wow!!! 000000000000000000this is string example....wow!!! ``` --- ### Example 2: Formatting Numeric Strings `zfill()` is commonly used to format numeric strings for consistent alignment (e.g., in serial numbers or dates). ```python # Formatting numbers with leading zeros print("42".zfill(5)) print("123".zfill(5)) print("7".zfill(5)) ``` **Output:** ```text 00042 00123 00007 ``` --- ## Key Considerations ### 1. Handling Sign Prefixes If the original string starts with a sign prefix (`+` or `-`), `zfill()` is smart enough to place the padding zeros **after** the sign character rather than before it. ```python # Negative and positive numeric strings print("-42".zfill(6)) print("+42".zfill(6)) ``` **Output:** ```text -00042 +00042 ``` ### 2. Width Less Than String Length If the `width` parameter is smaller than the length of the original string, the string is returned unmodified. It will not be truncated. ```python text = "Python" # The length of "Python" is 6. Requesting a width of 3 returns the original string. print(text.zfill(3)) ``` **Output:** ```text Python ```
← Att String IsdecimalAtt String Upper β†’