Files
python/20-24/lianxi-replace.py
2026-05-06 11:21:42 +08:00

67 lines
1.5 KiB
Python

def clean_user_input(user_input):
replacements = {
" ": " ", # 将双空格替换为单空格
"\t": " ", # 将制表符替换为空格
"\n": " ", # 将换行符替换为空格
"&": "and", # 将&符号替换为and
"@": "at", # 将@符号替换为at
}
# 替换
cleaned_input = user_input
for old, new in replacements.items():
cleaned_input = cleaned_input.replace(old, new)
# 去除收尾空格
cleaned_input = cleaned_input.strip()
return cleaned_input
dirty_input = "Hello world\t\n&@test"
clean_result = clean_user_input(dirty_input)
print("清洗前:", repr(dirty_input))
print("清洗后:", repr(clean_result))
def replace_email_template(template, user_data):
for key, val in user_data.items():
template = template.replace(f"{{{key}}}", val)
return template
# 定义邮件模板
email_template = """
Dear {name},
Thank you for your order #{order_id}.
Your total amount is ${amount}.
Best regards,
Customer Service
"""
# 定义用户数据
user_data = {"name": "Alice", "order_id": "12345", "amount": "99.99"}
final_email = replace_email_template(email_template, user_data)
print(final_email)
email_template = """
Dear {name},
Thank you for your order #{order_id}.
Your total amount is ${amount}.
Best regards,
Customer Service
"""
# 定义用户数据
user_data = {"name": "Alice", "order_id": "12345", "amount": "99.99"}
# 使用 `format()` 方法替换模板中的占位符
email = email_template.format(**user_data)
print(email)