字符串拼接
```python
value = 10
unit = "米"
result = str(value) + unit
print(result) 输出:10米
使用类表示
```python
class Quantity:
def __init__(self, value, unit):
self.value = value
self.unit = unit
def __str__(self):
return f"{self.value}{self.unit}"
q = Quantity(10, "米")
print(q) 输出:10米
字符串格式化
```python
temperature = 25.
formatted_temperature = f"{temperature}°C"
print(formatted_temperature) 输出:25.51°C
自定义函数
```python
import numpy as np
def num2str(num, unit_prefixs, base_unit_index):
x = np.log10(num)
exponent = np.floor(x)
unit_prefix = unit_prefixs[exponent + base_unit_index]
return f"{num / (10 exponent)}{unit_prefix}"
unit_prefixs = ['', 'k', 'M', 'G', 'T']
print(num2str(1000, unit_prefixs, 8)) 输出:1.0k
国际化方法
```python
-*- coding: utf-8 -*-
import gettext
设置翻译文件路径
locale_path = 'locale'
language_code = 'zh_CN'
初始化翻译
t = gettext.translation('messages', locale_path, languages=[language_code])
t.install()
使用_函数进行翻译
print(_("Hello")) 输出中文 "你好"
以上方法可以帮助你在Python中给数值添加单位。选择适合你需求的方法进行操作即可