YouTip LogoYouTip

Python3 String Translate

## Python3 String translate() Method In Python 3, the `translate()` method is a highly efficient built-in tool used for character translation and deletion. It maps specific characters in a string to other characters based on a translation table (typically created using `str.maketrans()`). This method is particularly useful for bulk character replacement, data sanitization, and stripping unwanted characters from text. --- ## Syntax The `translate()` method is available for `str`, `bytes`, and `bytearray` objects. However, their signatures and behaviors differ slightly: ```python # For Unicode strings (str) str.translate(table) # For bytes objects bytes.translate(table, delete=b'') # For bytearray objects bytearray.translate(table, delete=b'') ``` ### Parameters * **`table`**: * For **`str`**: A translation table (a dictionary or mapping) where keys are Unicode ordinals (integers) and values are Unicode ordinals, strings, or `None` (to delete the character). This table is most easily created using the static method `str.maketrans()`. * For **`bytes` / `bytearray`**: A bytes object of length 256, typically created using `bytes.maketrans()`. * **`delete`** *(Only available for `bytes` and `bytearray`)*: * A bytes object containing characters that should be removed from the source before applying the translation table. ### Return Value * Returns a new string, bytes, or bytearray object with the specified translations and/or deletions applied. The original object remains unchanged. --- ## How to Create a Translation Table with `maketrans()` Before using `translate()`, you usually need to generate a translation table using `maketrans()`. ### For Unicode Strings (`str.maketrans`) `str.maketrans()` can take up to three arguments: 1. **One argument (dict)**: A dictionary mapping Unicode ordinals (or characters) to their replacements. 2. **Two arguments (x, y)**: Two strings of equal length. Each character in `x` will be mapped to the character at the same index in `y`. 3. **Three arguments (x, y, z)**: The third argument `z` specifies a string of characters that should be mapped to `None` (i.e., deleted from the output). --- ## Code Examples ### Example 1: Basic Character Replacement in Strings This example demonstrates how to replace vowels with numbers using a translation table. ```python #!/usr/bin/python3 # Define input characters and their corresponding replacements intab = "aeiou" outtab = "12345" # Generate the translation table trantab = str.maketrans(intab, outtab) # Source string source_str = "this is string example....wow!!!" # Translate and print the result print(source_str.translate(trantab)) ``` **Output:** ```text th3s 3s str3ng 2x1mpl2....w4w!!! ``` --- ### Example 2: Deleting Characters in Unicode Strings You can use the 3-argument version of `str.maketrans()` to translate certain characters while completely removing others. ```python #!/usr/bin/python3 # Map 'a', 'b', 'c' to 'X', 'Y', 'Z', and delete '!', '.', and space ' ' intab = "abc" outtab = "XYZ" deletetab = "! ." trantab = str.maketrans(intab, outtab, deletetab) source_str = "abc! hello world..." print(source_str.translate(trantab)) ``` **Output:** ```text XYZhelloworld ``` --- ### Example 3: Translating and Deleting with `bytes` When working with binary data or ASCII-only `bytes` objects, you can pass the `delete` parameter directly to the `translate()` method. ```python #!/usr/bin/python3 # Create a translation table to convert lowercase ASCII to uppercase ASCII bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ') # Convert to uppercase and delete the character 'o' source_bytes = b'runoob' result = source_bytes.translate(bytes_tabtrans, b'o') print(result) ``` **Output:** ```text b'RUNB' ``` --- ## Key Considerations 1. **Performance**: The `translate()` method is implemented in C and is significantly faster than using multiple `.replace()` calls or regular expressions (`re.sub`) when performing multiple single-character replacements. 2. **Immutability**: Since Python strings and bytes are immutable, `translate()` does not modify the original object; it returns a brand-new copy. 3. **Type Consistency**: You cannot mix `str` and `bytes` operations. If you are working with a Unicode string, use `str.translate()` and `str.maketrans()`. If you are working with binary data, use `bytes.translate()` and `bytes.maketrans()`.
← Python3 Att List LenPython3 String Startswith β†’