分类 学习 下的文章

运算符描述实例
+=加法赋值运算符c += a 等效于 c = c + a
-=减法赋值运算符c -= a 等效于 c = c - a
*=乘法赋值运算符c = a 等效于 c = c a
/=除法赋值运算符c /= a 等效于 c = c / a
%=取模赋值运算符c %= a 等效于 c = c % a
**=幂赋值运算符c = a 等效于 c = c a
//=取整除赋值运算符c //= a 等效于 c = c // a

列举部分占位符

%d整数的占位符
%f小数的占位符
%%表示百分号(因为百分号代表了占位符,所以带占位符的字符串中要表示百分号必须写成%%)

一、 使用占位符%格式化

按序罗列式 适用于python2.6前,沿用至今 延用了C语言的输出格式

a=1.1
b=2
print("有两个数,分别是浮点数a= %f 和整数b= %d" %(a,b))

这种写法,必须在后方按照顺序罗列准备用于替换占位符的变量名称,能不能在前面直接指定用于替换的变量名称呢?

二、 使用format格式化

官方推荐 python2.6新增,沿用至今
格式:str.format

a=1.1
b=2
print("有两个数,分别是浮点数a= {}和整数b= {}".format(a,b)) 
# {key}称为索引,索引为空{}时,按照顺序从后方取值,可以使用01234这样的顺序的数字作为索引进行排序。
print("有两个数,分别是浮点数a= {0}和整数b= {1}".format(a,b))
# 也可以直接使用一个特定名称作为索引。
print("有两个数,分别是浮点数a= {num_a}和整数b= {num_b}".format(num_a=a,num_b=b))
# 你也可以把变量a,b替换为一个单引号包括的字符串,如:'1.1'

以上三个print语句都输出:有两个数,分别是浮点数a= 1.1和整数b= 2

三、 f-string格式化

直接指定式 适用于Python >= 3.6
f-string是在字符串前面加上 "f",{}直接使用变量、表达式等。

a=1.1
b=2
print(f"有两个数,分别是浮点数a= {a:.1f}和整数b= {b:d}")
# 为啥加个.1而不是直接写{a:f} ?f前面的.1指的是保留小数点后一位小数,不写.1输出的就是:1.100000

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

This is a website run on ipv6 Internet. ×
This is a website running on ipv6 Internet.✓

第一个句子里有两个动词,一个是be动词,一个是run,在英语上,语法规定,一个句子不能有2个动词,所以第二个要用动名词形式。---