今天写脚本,遇到了这种情况:需要上一个脚本的回参作为一个路径参数,我用的os.path.join()处理,因为这个路径参数在最后一位,但是没有考虑到如果路径参数在中间的话,这样的拼接就只能把后面的路径写死,会很挫,于是参考组内大神,利用字符串的format方法,这样可以灵活处理路径参数的位置。
下面来整理一下format()方法的一些基本用法:
1、利用format占位
#1、利用索引占位插入 print("Hello {1} {0}".format("Su", "Han.")) #2、利用名称插入 print("My name is {name}".format(name = "SuHan")) name= {'last_name': 'han', 'first_name': 'Su'} print('name: {last_name} {first_name}'.format(**name)) #**+参数,是将参数以字典形式导入;*+参数,是将参数以元组形式导入
2、利用format对齐
#9.3、对齐(<表示内容左对齐;>表示内容右对齐,^表示内容居中,需要配合width一起使用,width为宽度,就是距对齐处的距离; :号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充) print("{:>100}".format(1)) print("{:<100}".format(1)) print("{:*<10}".format("kitty")) print("{:_>10}".format("kitty")) print("{:$^50}".format("pitty")) >>> 1 >>> 1 >>> kitty***** >>> _____kitty >>> $$$$$$$$$$$$$$$$$$$$$$pitty$$$$$$$$$$$$$$$$$$$$$$$