python 基本运算符与格式化输出

python基本运算符

计算机可以进行的运算有很多种,可不只加减乘除这么简单,运算按种类可分为算数运算、比较运算、逻辑运算、赋值运算、成员运算、身份运算、位运算   

算数运算

Ps:假设变量:a=10b=20

  比较运算

  Ps:假设变量:a=10b=20

赋值运算

 Ps:假设变量:a=10b=20

 逻辑运算

ps:三者的优先级从高到低分别是:not,or,and

 

身份运算

is比较的是id
==比较的是值

 python格式化输出

%用法

整数的输出

 >>> print('%o' % 20)  八进制
 24

 >>> print('%d' % 20)  十进制
 20

 >>> print('%x' % 20)   十六进制
 14
View Code

 浮点数输出

 >>> print('%f' % 1.11)   默认保留6位小数
  1.110000
  
 >>> print('%.1f' % 1.11)   取1位小数
  1.1
  
  >>> print('%e' % 1.11)   默认6位小数,用科学计数法
  1.110000e+00
  
  >>> print('%.3e' % 1.11)   取3位小数,用科学计数法
  1.110e+00
  
  >>> print('%g' % 1111.1111)   默认6位有效数字
 1111.11
 
 >>> print('%.7g' % 1111.1111)   取7位有效数字
 1111.111
 
 >>> print('%.2g' % 1111.1111)   取2位有效数字,自动转换为科学计数法
 1.1e+03
View Code

字符串输出

  >>> print('%s' % 'hello world')   字符串输出
  hello world
  
  >>> print('%20s' % 'hello world')   右对齐,取20位,不够则补位
           hello world
           
  >>> print('%-20s' % 'hello world')   左对齐,取20位,不够则补位
  hello world   
  
  >>> print('%.2s' % 'hello world')   取2位
  he
  
  >>> print('%10.2s' % 'hello world')   右对齐,取2位
         he
         
  >>> print('%-10.2s' % 'hello world')   左对齐,取2位
  he     
View Code

format用法

相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’

  >>> print('{} {}'.format('hello','world'))   不带字段
  hello world
  
  >>> print('{0} {1}'.format('hello','world'))   带数字编号
  hello world
  
  >>> print('{0} {1} {0}'.format('hello','world'))   打乱顺序
  hello world hello
  
  >>> print('{1} {1} {0}'.format('hello','world'))
  world world hello
  
  >>> print('{a} {tom} {a}'.format(tom='hello',a='world'))   带关键字
  world hello world
View Code

 

 

 

转载于:https://www.cnblogs.com/dragon-123/p/10224348.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值