当前位置:   article > 正文

python输出文本对齐_如何在PYTHON里对文本进行对齐处理

jupyter notebook用print输出怎么对齐

1

打开JUPYTER NOTEBOOK,新建一个空白的PY文档。

732a12e265e7340f3e26929035b9763e20c2b4f1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

2

song = ["歌词", "晚风轻拂澎湖湾", "白浪逐沙滩", "没有椰林缀斜阳", "只是一片海蓝蓝", "坐在门前的矮墙上"]

新建一个歌词列表。

bff8683e21c2bbd6818eeb5b116186254093aef1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

3

for song_str in song:

print(song_str)

用遍历的方式把歌词打印出来,会发现位置比较乱。

9b2098254193cee8d65ad2a85a0ff2260c9aa8f1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

4

for song_str in song:

print(song_str.center())

字符串有center()这个方法可以用,但是必须加入参数。

0cdb2f0e1799e92ad4e6c4f3e1fec314f0c5a0f1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

5

for song_str in song:

print(song_str.center(5))

但是加入的参数要大于等于原有的字符长度会比较好。

c255efc595ee41c1c2792ae08d88912ca4ca9bf1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

6

for song_str in song:

print(song_str.center(10))

有了长度以后,还是有点不整齐。

ad121888912ca5caa6b616fb8bfc77f7990e94f1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

7

for song_str in song:

print("*%s*" %song_str.center(10))

用通配符来让整体观看好看一些。

dda98e4800fc77f7e650d993c8715fdb372090f1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

8

for song_str in song:

print("*%s*" % song_str.center(10, " "))

然后设置全角空格。

423041db3620b93a49d7a676ad0f8835dc8a8af1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

9

for song_str in song:

print("*%s*" % song_str.center(10, " "))

半角空格还是会有问题。

589f5b0788013870581fbc3f2d08a50f95fc83f1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

10

for song_str in song:

print("*%s*" % song_str.ljust(10, " "))

for song_str in song:

print("*%s*" % song_str.rjust(10, " "))

除了居中,还可以左对齐和右对齐。

95bd4e8c9bcec7f81f29db6e034ce54a2e27fbf1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

e6ae36066b0192ddad1e30401a87031c98c0f0f1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1

END

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/294610
推荐阅读
相关标签
  

闽ICP备14008679号