python3 0218 输入和输出、*、**

目录

python 几种输出方式

sys


python 几种输出方式

  • 表达式

  • print()函数

  • 标准输出文件可以用sys.stdout引用
  • 文件对象write(srt)方法,str写入输出到文件对象中,返回写入的长度
f = open('C:\\Users\\daily-practice\\test.txt', 'w')
std = f.write('Just Test 0218')
print(std)
  • str.format()函数格式话输出值
    1. 位置
    2. 关键字
  • 输出:A.B
    print('{}.{}'.format('A','B'))
    print('{first}.{second}'.format(first='A',second='B'))
    print('{0}.{second}'.format('A',second='B'))
    
    # 格式化结果,保留小数点后3位
    import math
    print('{0:.3f}'.format(math.pi))    // 3.142
    
    # 格式化用空格填充,美观结果
    print('{0:10}==>{1:3d}'.format('2.1', 33)) //2.1       ==> 33
    
    # 关键字格式化字典
    table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
    print('{0[Taobao]:d};{0[Runoob]:d};{0[Google]:d}'.format(table))  //3:2;1
    print('{Taobao:d};{Runoob:d};{Google:d}'.format(**table)) //3:2;1
    注意:
    1、**table,类似于以关键字传参,相当于Google=1,Runoob=2,Taobao=3
    2、*list,类似于位置传参
    // 演示调用函数,使用*、**
    def normal_func(arg1, arg2, arg3):
        print('arg1:', arg1)
        print('arg2:', arg2)
        print('arg3:', arg3)
    
    
    # *相当于位置传参,**相当于关键字传参
    args_list = ['A', 1, 'B']
    kwargs_dict = {'arg2': 'A', 'arg1': '1', 'arg3': 'B'}
    normal_func(*args_list)
    normal_func(**kwargs_dict)
    
    # 定义函数使用*args 、 **kwargs,接收可变长度的列表或字典
    args_list = ['A', 1, 'B']
    kwargs_dict = {'arg2': 'A', 'arg1': '1', 'arg3': 'B'}
    
    
    def test_args(normal_arg, *args):
        print('normal_arg:', normal_arg)
        for arg in args:
            print('other_arg:', arg)
    
    
    def test_kwargs(name, **kwargs):
        print(name)
        if kwargs is not None:
            for key in kwargs:
                print('{}={}'.format(key, kwargs[key]))
    
    
    test_args('A', *args_list)
    test_kwargs('xiaohong', **kwargs_dict)
    
    
    实例:
    import yaml
    
    
    def test_func(db, name):
        print(db)
        print(name)
    
    
    yamlpath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'config.yaml')
    with open(yamlpath, 'r', encoding='utf-8') as f:
        req_data = yaml.load(f.read(), Loader=yaml.FullLoader)
        print(req_data)   //{'db': 'test', 'name': 'cyw'}
        print(type(req_data)) //dict
    
    # 使用场景:例如从yaml文件读取mongo的用户名、密码等等,如果之前调用方式需要req_data['db']、req_data['name'],yaml有多少参数,需要调用几次,太复杂,现在只需将yaml的内容**当作关键字参数传入,这样就满足需求了
    test_func(**req_data)

     

  • %操作符格式字符串
    1. print("%d,%5.3f" %(100,math.pi))  //100,3.142
  • repr()将输出值转换成字符串, 产生一个解释器易读的表达形式
    s = 'hello, 2021\nend'
    print(str(s),"Same print")
    print(repr(s),"Same print") //可以保留字符串中的特殊字符
    
    输出的结果:
    hello, 2021
    end Same print
    'hello, 2021\nend' Same print
    

     

  • str()将输出值转换成字符串, 函数返回一个用户易读的表达形式
    格式化
    
    将字符变成字符串后,用内置方法,可以格式化输出
    s = 0.125
    s1 = repr(s).rjust(8,'`')
    print(len(s1))
    print(s1)
    
    结果:
    8
    ```0.125
    
    rjust(width,fillchar)
        将字符右对齐,不满长度,使用fillchar填充
        width:填充后的长度
        fillchar:用于填充的字符
    
    类似的方法:ljust(),center()
    zfill(),在数字左边填充0

     

python 读入

  • 读取键盘输入

sys

  • sys.argv(),命令行执行时,由系统传递给程序,argv[0]返回被调用脚本的文件名或全路径,argv[1:]返回传入的参数

print(sys.argv[:])   # ['0218.py', 'hello', 'all', '3']

for i in sys.argv:
    print(i)

# 0218.py
  hello
  all
  3
  • sys.stdout.write(str) 将str写入标准输出中,也就是控制台
    结合file对象,将标准输出从控制台写入文件中
    file = sys.stdout //保存原始输出对象
    sys.stdout = open('C:\\User\\daily-practice\\test.txt', 'w') 将标准输出重定向到open 的file对象
    print('hell')
    print('12345')
    sys.stdout.close()  //关闭上述open的对象
    sys.stdout = file   //将标准输出,再次指向原始对象
    print('结果时')
    
    
    
    
    #打印的结果:
    结果时
    
    #test.txt的内容:
    hell
    12345

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值