2007-06-12
Python Cook 1.4 排列字符
需求:
想要让输出的字符能够按照左对齐,右对齐,居中对齐的格式排列.这对于生成格式化的文本很重要.
让人回想起在C语言中的printf("%nd")的格式,其中n如果是-的,就是右对齐,不过好像没有居中对齐的概念啊.
讨论:
在Python中,是用str的rjust,ljust,center方法来实现上述的功能.看下面的例子:
>>> print '|','Hello'.ljust(15),'|','Hello'.rjust(15),'|','Hello'.center(15),'|'
| Hello | Hello | Hello |
挺酷的,是吧,第一次用这个功能的时候,心里有说不出的方便的感觉,呵呵.
相关说明:
ljust(...)
S.ljust(width[, fillchar]) -> string
Return S left justified in a string of length width. Padding is
done using the specified fill character (default is a space).
rjust(...)
S.rjust(width[, fillchar]) -> string
Return S right justified in a string of length width. Padding is
done using the specified fill character (default is a space)
center(...)
S.center(width[, fillchar]) -> string
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
想要让输出的字符能够按照左对齐,右对齐,居中对齐的格式排列.这对于生成格式化的文本很重要.
让人回想起在C语言中的printf("%nd")的格式,其中n如果是-的,就是右对齐,不过好像没有居中对齐的概念啊.
讨论:
在Python中,是用str的rjust,ljust,center方法来实现上述的功能.看下面的例子:
>>> print '|','Hello'.ljust(15),'|','Hello'.rjust(15),'|','Hello'.center(15),'|'
| Hello | Hello | Hello |
挺酷的,是吧,第一次用这个功能的时候,心里有说不出的方便的感觉,呵呵.
相关说明:
ljust(...)
S.ljust(width[, fillchar]) -> string
Return S left justified in a string of length width. Padding is
done using the specified fill character (default is a space).
rjust(...)
S.rjust(width[, fillchar]) -> string
Return S right justified in a string of length width. Padding is
done using the specified fill character (default is a space)
center(...)
S.center(width[, fillchar]) -> string
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
标签: Python