python 字符串填充0

博客介绍了Python中字符串补0的方法。zfill方法可给字符串和负数前面补0,对于纯数字,还能通过格式化方式补0,这些方法在实际编程中很有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python中有一个zfill方法用来给字符串前面补0,非常有用

= "123"
= n.zfill(5)
assert == "00123"

zfill()也可以给负数补0

= "-123"
= n.zfill(5)
assert == "-0123"

对于纯数字,我们也可以通过格式化的方式来补0

= 123
= "%05d" % n
assert == "00123"
### Python字符串填充和对齐方法 #### 使用 `str.ljust()`、`str.rjust()` 和 `str.center()` 为了实现字符串的左对齐、右对齐以及居中对齐,可以分别使用 `str.ljust(width)`、`str.rjust(width)` 和 `str.center(width)` 方法。这些方法允许指定一个总宽度,并在必要时用空格或其他字符填充剩余空间。 ```python text = "hello" # 左对齐 (默认填充为空格) left_aligned = text.ljust(10) # 右对齐 (默认填充为空格) right_aligned = text.rjust(10) # 居中对齐 (默认填充为空格) centered = text.center(10) print(f"'{left_aligned}'") # 'hello ' print(f"'{right_aligned}'") # ' hello' print(f"'{centered}'") # ' hello ' ``` 上述代码展示了如何利用这三个函数来调整文本的位置[^1]。 #### 自定义填充字符 除了使用默认的空白作为填充外,还可以自定义用于填补的空间内的任意单个字符: ```python custom_fill_left = text.ljust(10, '*') custom_fill_right = text.rjust(10, '=') custom_fill_center= text.center(10, '-') print(f"'{custom_fill_left}'") # 'hello*****' print(f"'{custom_fill_right}'") # '=====hello' print(f"'{custom_fill_center}'") # '--hello---' ``` 这里可以看到,在指定了不同的填充字符之后,输出的结果会相应变化[^3]。 #### 格式化字符串中的对齐方式 另一种常见的做法是在格式化字符串时应用对齐选项。这可以通过 f-string 或者 format 函数完成: ```python formatted_string = f"{text:>10}" # 右对齐 alternative_formatting = "{:<10}".format(text) # 左对齐 print(f"'{formatted_string}'") # ' hello' print(f"'{alternative_formatting}'") # 'hello ' ``` 这种语法提供了简洁的方式来控制最终显示的效果[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值