str的函数
center(text: str, width: int, fillchar=’ ') 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格
def center(text: str, width: int, fillchar=' '):
'''
:param text: 需要操作的字符串
:param width: 宽度
:param fillchar: 填充字符;默认为空格
:return: 填充后的字符串
'''
if len(fillchar) != 1:
eval('TypeError:The fill character must be exactly one character long') # 填充字符的长度必须正好为一个字符
length = len(text)
if length >= width:
return text
else:
width -= length
width1 = width//2
if width/2 == width1:
return fillchar*width1+text+fillchar*width1
else:
return fillchar*(width1+1)+text+fillchar*width1
rjsut(text: str, width: int, fillchar=’ ') 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
def rjsut(text: str, width: int, fillchar=' '):
'''
:param text: 需要操作的字符串
:param width: 宽度
:param fillchar: 填充字符;默认为空格
:return: 填充后的字符串
'''
if len(fillchar) != 1:
eval('TypeError:The fill character must be exactly one character long') # 填充字符的长度必须正好为一个字符
length = len(text)
if length >= width:
return text
else:
width -= length
return fillchar*width+text
ljust(text: str, width: int, fillchar=’ ') 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
def ljust(text: str, width: int, fillchar=' '):
'''
:param text: 需要操作的字符串
:param width: 宽度
:param fillchar: 填充字符;默认为空格
:return: 填充后的字符串
'''
if len(fillchar) != 1:
eval('TypeError:The fill character must be exactly one character long')
length = len(text)
if length >= width:
return text
else:
width -= length
return text+fillchar*width
zfill(text: str, width: int) 返回长度为 width 的字符串,原字符串右对齐,前面填充0
def zfill(text: str, width: int):
'''
:param text: 需要操作的字符串
:param width: 宽度
:param fillchar: 填充字符;默认为空格
:return: 填充后的字符串
'''
length = len(text)
if length >= width:
return text
else</