python学习------指定字符串补全空格
需求:如果希望字符串的长度固定,给定的字符串又不够长度,我们可以通过rjust,ljust和center三个方法来给字符串补全空格。如果是数字型先将其转为字符,再使用rjust,ljust和center三个方法。
实现:
一、rjust,向右对其,在左边补空格
#
1
2
3
4
5
6
7
8
9
10
11
12
|
vim test.py
#/usr/bin/evn python
# -*- coding: utf-8 -*-
import
sys
reload
(sys)
sys.setdefaultencoding(
'utf8'
)
m
=
"#"
a
=
123
s
=
str
(a).rjust(
5
)
print
m
+
s
+
m
输出结果: python test.py
# 123#
|
二、ljust,向左对其,在右边补空格
1
2
3
4
5
6
7
8
9
10
11
12
|
# vim test.py
#/usr/bin/evn python
# -*- coding: utf-8 -*-
import
sys
reload
(sys)
sys.setdefaultencoding(
'utf8'
)
m
=
"#"
a
=
123
s
=
str
(a).ljust(
5
)
print
m
+
s
+
m
输出结果:python test.py
#123 #
|
三、center,让字符串居中,在左右补空格
1
2
3
4
5
6
7
8
9
10
11
12
|
# vim test.py
#/usr/bin/evn python
# -*- coding: utf-8 -*-
import
sys
reload
(sys)
sys.setdefaultencoding(
'utf8'
)
m
=
"#"
a
=
123
s
=
str
(a).center(
5
)
print
m
+
s
+
m
输出结果:python test.py
# 123 #
|
本文转自独弹古调 51CTO博客,原文链接:http://blog.51cto.com/hunkz/1845463,如需转载请自行联系原作者