python 填充字符串
时间: 2023-12-29 10:04:15 浏览: 33
在Python中,可以使用字符串的内置方法`str.ljust()`、`str.rjust()`和`str.center()`来填充字符串。这些方法都接受一个整数参数,表示字符串的总宽度,以及一个可选的填充字符参数,表示用于填充字符串的字符,默认为空格。
下面是三种填充字符串的方法的示例代码:
1. `str.ljust()`方法:左对齐并用空格填充字符串
```python
s = 'hello'
width = 10
padded_s = s.ljust(width)
print(padded_s) # 输出:'hello '
```
2. `str.rjust()`方法:右对齐并用指定字符填充字符串
```python
s = 'hello'
width = 10
fillchar = '*'
padded_s = s.rjust(width, fillchar)
print(padded_s) # 输出:'*****hello'
```
3. `str.center()`方法:居中对齐并用指定字符填充字符串
```python
s = 'hello'
width = 11
fillchar = '-'
padded_s = s.center(width, fillchar)
print(padded_s) # 输出:'---hello---'
```
另外,还可以使用`format()`函数来填充字符串。`format()`函数可以接受一个格式化字符串,其中用花括号{}表示要填充的位置,可以在花括号中使用冒号:来指定填充的宽度和填充字符。例如,要把字符串"hello"左侧填充10个空格,可以使用如下代码:
```python
s = 'hello'
padded_s = '{:>10}'.format(s)
print(padded_s) # 输出:' hello'
```