python序列

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里的参数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值