Python ljust()字符串左对齐方法详解

  • 内容
  • 评论
  • 相关

Python ljust() 方法的功能是向指定字符串的右侧填充指定字符,从而达到左对齐文本的目的。

ljust() 方法的基本格式如下:

S.ljust(width[, fillchar])

其中各个参数的含义如下:

  • S:表示要进行填充的字符串;
  • width:表示包括 S 本身长度在内,字符串要占的总长度;
  • fillchar:作为可选参数,用来指定填充字符串时所用的字符,默认情况使用空格。

【例 1】

S = 'http://c.biancheng.net/python/'
addr = 'http://c.biancheng.net'
print(S.ljust(35))
print(addr.ljust(35))

输出结果为:

http://c.biancheng.net/python/    
http://c.biancheng.net            

注意,该输出结果中除了明显可见的网址字符串外,其后还有空格字符存在,每行一共 35 个字符长度。

【例 2】

S = 'http://c.biancheng.net/python/'
addr = 'http://c.biancheng.net'
print(S.ljust(35,'-'))
print(addr.ljust(35,'-'))

输出结果为:

http://c.biancheng.net/python/-----
http://c.biancheng.net-------------

此程序和例 1 的唯一区别是,填充字符从空格改为‘-’。

本文标题:Python ljust()字符串左对齐方法详解

本文地址:http://www.hosteonscn.com/6868.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注