Python的容器分为序列(列表、元组)和映射(字典)、集合
序列的切片
序列[start🔚step]
当step为负数时,是从右边往左边移动,start要比end大
当step为正数时,是从左边往右边移动
切片的第一个索引包含在内,第二个索引不包含在内
在指定位置打印文字
sentence=input("请输入一句话:")
screen_width = 100
text_width = len(sentence)
print(text_width)
box_width = text_width + 6
left_width = (screen_width - box_width) // 2
print(' ' * left_width + '+' + '-' * (box_width - 2) + '+')
print(' ' * left_width + '| ' + ' ' * text_width + ' |')
print(' ' * left_width +'| '+sentence+' |')
print(' ' * left_width + '| ' + ' ' * text_width + ' |')
print(' ' * left_width + '+' + '-' * (box_width - 2) + '+')
但是此方法存在一个问题,len()函数只会计算序列的长度,不会计算在Python中的实际宽度,所以打印中文的时候会出问题
wcwidth模块
系统提供 wcwidth和wcswidth函数, 这些函数返回一个unicode字符串预期占用的单元数。
def wc_rjust(text, length, padding=' '):
from wcwidth import wcswidth
return text+padding * max(0, (length - wcswidth(text)))
print(wc_rjust('你好', 10, '_'))
print( 10* '_')
代码运行结果
用wcwidth计算中文宽度虽然还是有一定的误差,但是比较小
对齐输出文本
参考链接:https://blog.csdn.net/weixin_45715159/article/details/106176454
import wcwidth
def print_format(string,way,width,fill= ' ',ed = ''):#格式输出函数,默认格式填充用单空格,不换行。
try:
count = wcwidth.wcswidth(string)-len(string) #宽字符数量
width = width - count if width >= count else 0
print('{0:{1}{2}{3}}'.format(string,fill,way,width),end = ed,flush=True)
except:
print('print_format函数参数输入错误!')
print_format('你好ss','^',10,'*','\n')
print_format('你好s','^',10,'*','\n')
format格式化输出
^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
‘{0:{1}{2}{3}}’.format(string,fill,way,width),end = ed,flush=True)
0,1,2,3分别指的是format里的参数