python学习------指定字符串补全空格

简介:

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 = "#"
=  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 = "#"
=  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 = "#"
=  123
s = str (a).center( 5 )
print  m + s + m
输出结果:python test.py 
# 123 #








          本文转自独弹古调  51CTO博客,原文链接:http://blog.51cto.com/hunkz/1845463,如需转载请自行联系原作者


相关文章
|
8天前
|
Python
python函数的参数学习
学习Python函数参数涉及五个方面:1) 位置参数按顺序传递,如`func(1, 2, 3)`;2) 关键字参数通过名称传值,如`func(a=1, b=2, c=3)`;3) 默认参数设定默认值,如`func(a, b, c=0)`;4) 可变参数用*和**接收任意数量的位置和关键字参数,如`func(1, 2, 3, a=4, b=5, c=6)`;5) 参数组合结合不同类型的参数,如`func(1, 2, 3, a=4, b=5, c=6)`。
13 1
|
11天前
|
Python
1167: 分离字符串(PYTHON)
1167: 分离字符串(PYTHON)
|
11天前
|
Python
Python文件操作学习应用案例详解
【4月更文挑战第7天】Python文件操作包括打开、读取、写入和关闭文件。使用`open()`函数以指定模式(如'r'、'w'、'a'或'r+')打开文件,然后用`read()`读取全部内容,`readline()`逐行读取,`write()`写入字符串。最后,别忘了用`close()`关闭文件,确保资源释放。
17 1
|
3天前
|
Python
python学习3-选择结构、bool值、pass语句
python学习3-选择结构、bool值、pass语句
|
2天前
|
机器学习/深度学习 算法 Python
使用Python实现集成学习算法:Bagging与Boosting
使用Python实现集成学习算法:Bagging与Boosting
11 0
|
3天前
|
Python
python学习14-模块与包
python学习14-模块与包
|
3天前
|
Python
python学习12-类对象和实例对象
python学习12-类对象和实例对象
|
3天前
|
数据采集 Python
python学习9-字符串
python学习9-字符串
|
3天前
|
Python
python学习10-函数
python学习10-函数
|
3天前
|
存储 索引 Python
python学习7-元组
python学习7-元组

热门文章

最新文章