Python中左对齐和右对齐
时间: 2023-12-25 20:29:31 浏览: 29
在Python中,可以使用字符串的`ljust()`方法进行左对齐,使用`rjust()`方法进行右对齐。这两个方法都接受一个参数,用于指定字符串的总长度,如果字符串长度不足,则会在字符串的右侧(左对齐)或左侧(右对齐)填充指定的字符,默认为空格。
以下是一个示例代码:
```python
text = "Python"
left_aligned = text.ljust(10)
right_aligned = text.rjust(10)
print("Left aligned:", left_aligned) # 输出:Python
print("Right aligned:", right_aligned) # 输出: Python
```
在上面的示例中,字符串"Python"被左对齐和右对齐到长度为10的字符串,左对齐时在右侧填充空格,右对齐时在左侧填充空格。
相关问题
python中左右对齐输出
可以使用字符串的方法 `ljust()` 和 `rjust()` 来实现左右对齐输出。
`ljust()` 方法将字符串左对齐,并使用指定的填充字符填充字符串到指定的宽度。例如:
```python
text = 'hello'
width = 10
fillchar = '-'
print(text.ljust(width, fillchar))
# 输出:hello-----
```
`rjust()` 方法将字符串右对齐,并使用指定的填充字符填充字符串到指定的宽度。例如:
```python
text = 'hello'
width = 10
fillchar = '-'
print(text.rjust(width, fillchar))
# 输出:-----hello
```
如果不指定填充字符,则默认使用空格进行填充。例如:
```python
text = 'hello'
width = 10
print(text.ljust(width))
# 输出:hello
print(text.rjust(width))
# 输出: hello
```
python format左对齐右对齐
在Python中,可以使用字符串的format方法来对齐字符串。
左对齐:使用“<”符号来指定左对齐。例如,"{:<10}".format("hello")表示将字符串"hello"左对齐,并在其后添加6个空格,使其总长度为10。
右对齐:使用“>”符号来指定右对齐。例如,"{:>10}".format("hello")表示将字符串"hello"右对齐,并在其前添加6个空格,使其总长度为10。
下面是一些示例:
```
# 左对齐
print("{:<10}".format("hello"))
print("{:<10}".format("world"))
# 右对齐
print("{:>10}".format("hello"))
print("{:>10}".format("world"))
```
输出:
```
hello
world
hello
world
```