python之字符串填充和对齐

本文介绍了Python中字符串对齐和填充的方法,包括居中、左对齐、右对齐及数字0填充等操作,通过实例展示了不同场景下字符串格式化的应用。
函数名说明
A.center(n【,B】)将字符串A居中 ,len(A)>n返回A,len(A)<n,用字符串B填充(默认为空格)
A.ljust(n【,B】)将字符串A左对齐,同上
A.rjust(n【,B】)将字符串A右对齐 ,同上
A.zfill()将字符串右对齐,剩余0补齐

将字符串居中对齐,左右对齐,30为总字符长度,默认用空格填充

a='I love China'
print(a.center(30))
print(a.ljust(30,'-'))
print(a.rjust(30,'_'))

字符串右对齐,剩余用空格补齐

a="I love China"
print(a.zfill(20))

打印三角形、菱形
https://blog.youkuaiyun.com/GrofChen/article/details/92609284

### 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]。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值