在Python中,给数值添加单位通常有以下几种方法:
字符串拼接
value = 10unit = "米"result = str(value) + unitprint(result) 输出:10米
使用类
创建一个表示带单位的数值的类,可以方便地格式化输出,同时保持数值的原始类型。
class Quantity:def __init__(self, value, unit):self.value = valueself.unit = unitdef __str__(self):return f"{self.value}{self.unit}"q = Quantity(10, "米")print(q) 输出:10米

字符串格式化
使用f-string格式化方法,这是Python 3.6及以上版本中推荐的方式。
temperature = 25.formatted_temperature = f"{temperature}°C"print(formatted_temperature) 输出:25.51°C
正则表达式
如果需要处理更复杂的字符串,如包含单位的文本,可以使用正则表达式。
import retest_string = 'blah blah 5/8 blah blah 60lbs blah blah 1 /8'pattern = r"(?:(?P[1-9]\d*)(?:\s*\/\d*)?)(?:\s*(?P \\"|lbs|oz))?" matches = re.finditer(pattern, test_string)for match in matches:numerator = match.group('numerator')unit = match.group('unit')print(f"{numerator}{unit}")
以上方法可以根据具体需求选择使用。
