Python 字符串和 数字(int、float、Decimal、Fraction 等) 的一些使用技巧

Python 字符串和 数字(int、float、Decimal、Fraction 等) 的一些使用技巧

一、字符串使用技巧

1.f-string 高级格式化(推荐)

name = "Alice"
age = 25
pi = 3.1415926
print(f"Hello {name}, you are {age} years old, π≈{pi:.2f}")
# 输出: Hello Alice, you are 25 years old, π≈3.14

支持表达式

print(f"Next year you'll be {age + 1}")
print(f"{name.upper()} has {len(name)} letters.")

2.高级切片与步长

s = "abcdefg"
print(s[::-1])   # gfedcba 反转字符串
print(s[::2])    # aceg  每隔一个取字符

3.高效拼接与 join

parts = ["Python", "高级", "用法"]
print(" ".join(parts))  # 比字符串相加更高效(尤其是循环拼接时)

4.高级替换与正则提取

import re
s = "价格:¥123.45 元"
price = re.search(r"¥(\d+\.\d+)", s)
print(price.group(1))  # 123.45

5.translate + maketrans 批量替换

s = "hello world"
table = str.maketrans("hw", "HW")
print(s.translate(table))  # Hello World

6.strip / partition / splitlines / split

s = "  a=b=c  "
print(s.strip())            # a=b=c
print(s.partition("="))     # ('a', '=', 'b=c')
print("a\nb\nc".splitlines())  # ['a', 'b', 'c']
print(s.split('='))  # ['  a', 'b', 'c  ']

二、数字使用技巧

1.浮点精度问题与 Decimal

from decimal import Decimal, getcontext
getcontext().prec = 10  # 设置精度
print(Decimal("0.1") + Decimal("0.2"))  # 0.3 (精确)

2.分数表示 — Fraction

from fractions import Fraction
f = Fraction(3, 4) + Fraction(1, 2)
print(f)  # 5/4
print(float(f))  # 1.25

3.divmod, pow 三目计算

a, b = 17, 5
print(divmod(a, b))  # (3, 2)
print(pow(2, 10))    # 1024
print(pow(2, 3, 5))  # (2**3) % 5 = 3

4.数字格式化

print(f"{n:,.2f}")  # 1,234,567.89
print(f"{n:e}")     # 1.234568e+06

5.复数与数学扩展

结合 cmath 模块可计算复数开方、对数、指数等。

z = 3 + 4j
print(abs(z))       # 5.0
print(z.real, z.imag)

三、综合技巧:字符串与数字结合

1.使用 format_map 结合字典

data = {"name": "Alice", "age": 25}
print("{name}今年{age}岁".format_map(data))

2.正则提取数字

import re
s = "总价为 ¥123.45 元"
price = float(re.search(r"(\d+\.\d+)", s).group(1))

3.类型安全的拼接

num = 10
s = f"结果是:{num:,d}"  # 千分位整数
print(s)  # 结果是:10

本文章的原文地址
GitHub主页

posted @ 2025-10-23 16:23  星尘的博客  阅读(46)  评论(0)    收藏  举报