zoukankan      html  css  js  c++  java
  • 与用户交互以及格式化输出

    Python的与用户交互

    input('请输入帐号')
    input('请输入密码')
    

    ​ 注意:input接受的是字符串

    Python2的input和raw_input(了解)

    • Python2的raw_input就是python3的input

    • python2的input需要用户自己输入数据类型

    格式化输出

    • 把字符串按照一定格式打印或者填充

    占位符

    • 在字符串中,利用%来表示一个特殊的含义,对字符进行格式化
    • %d:后面应该放入一个整数
    • %s:后面应该放入一个字符串
    • 如果字符串中有占位符,则有几个占位符必须有几个实际内容代替,或者一个也没有
    name = 'test'
    age = 19
    print('My name is %s, my age is %d' % (name, age))
    

    my name is test, my age is 19

    format函数格式化字符串

    • 在使用上,用{}和:代替%号,后面跟format与参数完成
    1. {}内不填参数
    name = 'test'
    age = 19
    
    print('My name is {}, my age is {}.'.format(name, age))
    

    My name is test, my age is 19.

    1. {}内填写索引值
    name = 'test'
    age = 19
    
    print('My name is {1}, my age is {0}.'.format(age, name))
    

    My name is test, my age is 19.

    1. {}内填写准确变量名
    name = 'test'
    age = 19
    
    print('My name is {name}, my age is {age}.'.format(name=name, age=age))
    

    My name is test, my age is 19.

    f-string格式化(方便)

    • 和format有些类似,在引号前放一个f,后面需要格式化的地方用{变量名}即可
    • :.2f :保留两位小数
    name = 'test'
    age = 19
    
    print(f'My name is {name}, my age is {age}.')
    print(f'My name is {name}, my age is {age:.2f}.')
    
    

    My name is test, my age is 19.
    My name is test, my age is 19.00.

  • 相关阅读:
    freopen
    字符
    map映射
    P3512 [POI2010]PIL-Pilots-洛谷luogu
    快读
    单调队列&单调栈
    简写
    邻接表&链式前向星
    mysql参数详解
    网络管理指南
  • 原文地址:https://www.cnblogs.com/lucky75/p/10900615.html
Copyright © 2011-2022 走看看