杰瑞科技汇

Python maketrans,如何实现字符替换映射?

Of course! In Python, str.maketrans() is a static method that creates a translation table. This table is then used with the str.translate() method to perform character-by-character substitutions.

Python maketrans,如何实现字符替换映射?-图1
(图片来源网络,侵删)

Let's break it down.

What is a Translation Table?

A translation table is essentially a mapping that tells Python which characters to replace and what to replace them with. It's like a secret codebook for strings.


The Basic Syntax and Purpose

str.maketrans() is called on the str class itself, not on a string instance.

# The basic syntax
translation_table = str.maketrans(x, y, z)

The method has three forms, depending on the arguments you provide.

Python maketrans,如何实现字符替换映射?-图2
(图片来源网络,侵删)

Form 1: Two Equal-Length Strings (Character-to-Character Mapping)

This is the most common form. You provide two strings of the same length. The first string contains the characters you want to find, and the second string contains the characters you want to replace them with.

How it works:

  • For each character at index i in the first string, it maps to the character at index i in the second string.
  • Characters not in the first string are left unchanged.

Example: Creating a Simple Cipher

Let's create a simple "ROT13" style cipher where we shift letters.

# Define the characters to replace and their replacements
from_chars = "abcdefghijklmnopqrstuvwxyz"
to_chars   = "nopqrstuvwxyzabcdefghijklm"
# Create the translation table
cipher_table = str.maketrans(from_chars, to_chars)
# The original text
original_text = "hello world, this is a test."
# Use the .translate() method with the table
encoded_text = original_text.translate(cipher_table)
print(f"Original:  {original_text}")
print(f"Encoded:   {encoded_text}")
# To decode, we just use the same table again!
decoded_text = encoded_text.translate(cipher_table)
print(f"Decoded:   {decoded_text}")

Output:

Original:  hello world, this is a test.
Encoded:   uryyb jbeyq, guvf vf n grfg.
Decoded:   hello world, this is a test.

Form 2: A Single Dictionary (Flexible Character-to-Character or Character-to-String Mapping)

This form is more powerful. You pass a dictionary to str.maketrans().

  • Keys: The characters you want to replace.
  • Values: The characters (or even strings!) you want to replace them with.

Example: Replacing Punctuation with Words

Let's say we want to replace punctuation marks with their full word equivalents.

# Create a dictionary for the mapping
punctuation_map = {
    '.': ' period ',
    ',': ' comma ',
    '!': ' exclamation ',
    '?': ' question mark '
}
# Create the translation table from the dictionary
punct_table = str.maketrans(punctuation_map)
# The original text
text = "Hello, world! How are you?"
# Apply the translation
cleaned_text = text.translate(punct_table)
print(f"Original:  {text}")
print(f"Cleaned:   {cleaned_text}")

Output:

Original:  Hello, world! How are you?
Cleaned:   Hello  comma  world  exclamation  How are you  question mark 

Notice how the comma and exclamation mark were replaced with longer strings. This is a key advantage of the dictionary form.


Form 3: One String and One Dictionary (Combining Approaches)

This is a hybrid form. You provide one string and one dictionary.

  • The string argument specifies characters to be deleted.
  • The dictionary argument specifies the replacement mapping (same as Form 2).

This is useful for removing unwanted characters while also replacing others.

Example: Removing Vowels and Replacing Punctuation

Let's remove all vowels (a, e, i, o, u) and replace the exclamation mark with the word "wow".

# Characters to be deleted
delete_chars = "aeiou"
# Replacement mapping
replace_map = { '!': 'wow' }
# Create the combined translation table
combined_table = str.maketrans(delete_chars, '', replace_map)
# The original text
text = "Hello, world! This is amazing!"
# Apply the translation
result = text.translate(combined_table)
print(f"Original:  {text}")
print(f"Result:    {result}")

How it works:

  1. It sees delete_chars = "aeiou", so it will remove all vowels.
  2. It sees replace_map = { '!': 'wow' }, so it will replace with wow.
  3. The comma is not in either the delete list or the replace map, so it remains.

Output:

Original:  Hello, world! This is amazing!
Result:    Hll, wrld! Ths s mzmng!

Summary Table

Form Arguments What it Does Example Use Case
Two Strings str.maketrans(from_str, to_str) Creates a 1-to-1 character mapping. from_str[i] maps to to_str[i]. Simple ciphers, character substitutions.
One Dictionary str.maketrans(mapping_dict) Creates a flexible mapping. Keys (chars) are replaced by values (chars or strings). Replacing punctuation with words, custom filters.
String + Dictionary str.maketrans(delete_str, '', mapping_dict) Deletes characters in delete_str AND performs the replacements defined in mapping_dict. Cleaning text by removing chars and replacing others.

Key Takeaway

str.maketrans() is the setup step. It creates a reusable "rulebook" (the translation table). The actual transformation of a string happens when you call the .translate() method on a string and pass that rulebook to it.

# Step 1: Create the rulebook
table = str.maketrans('abc', '123')
# Step 2: Apply the rulebook to a string
my_string = "a b c d e"
new_string = my_string.translate(table)
print(new_string) # Output: "1 2 3 d e"
分享:
扫描分享到社交APP
上一篇
下一篇