python3 print 居中
时间: 2023-11-27 09:02:57 浏览: 40
可以使用字符串的 `center()` 方法来实现居中对齐。例如:
```
text = "hello"
print(text.center(10))
```
这将输出:
```
hello
```
其中,`center(10)` 表示将字符串居中对齐,总宽度为 10 个字符。如果字符串不足 10 个字符,会在两侧自动添加空格。如果字符串超过 10 个字符,则不会进行截断,而是原样输出。
相关问题
python的print函数居中输出
在Python中,可以使用字符串的`center()`方法来实现居中输出。`center()`方法接受一个整数参数,表示输出的总宽度,如果指定的宽度大于字符串的长度,则会在两侧填充空格使其居中。
下面是一个示例代码:
```python
text = "Hello, World!"
width = 20
print(text.center(width))
```
输出结果为:
```
Hello, World!
```
在上面的示例中,`text`是要输出的字符串,`width`是指定的总宽度。`center()`方法会根据指定的宽度,在字符串两侧填充空格,使其居中输出。
Python用print居中输出杭州八景
下面是Python的代码:
```
poetry = "杭州八景:\n\t曲院风荷\n\t西湖断桥\n\t上城龙井\n\t临安春雨\n\t雷峰夕照\n\t岳坟晓钟\n\t南宋御街\n\t河坊街夜市"
# 这是杭州八景的诗句,用\n表示换行,用\t表示缩进
print(poetry.center(30)) # 使用center方法居中输出八景
```
输出结果如下:
```
杭州八景:
曲院风荷
西湖断桥
上城龙井
临安春雨
雷峰夕照
岳坟晓钟
南宋御街
河坊街夜市
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)