以往C++交换代码至少需要三行
tmp=a; a=b; b=tmp;
python只需一行
a,b=b,a
name="Jack" print("Hi,I'm"+name) #以往 print("Hi,I'm %s" %(name)) #字符串格式化一 print("Hi,I'm {}".format(name)) #字符串格式化二 print(f"Hi,I'm {name}") #字符串格式化三 3.6之后版本可用
#所有字母大写化 fruit=["apple","banana","orange"] fruit=[x.upper() for x in fruit]
#筛选或过滤列表元素 fruit=["apple","banana","orange"] fruit=[x for x in fruit if x.startswith("a")] #运行结果 ['apple']
#通过enumerate函数获取列表索引 fruit=["apple","banana","orange"] for i,x in enumerate(fruit): print(i,x) #i是索引,x是值
#通过reverse函数反向遍历列表 fruit=["apple","banana","orange"] for i,x in enumerate(reverse(fruit)): print(i,x) #i是索引,x是值
#通过sorted函数反向遍历列表 fruit=["apple","banana","orange"] for i,x in enumerate(sorted(fruit)): print(i,x) #i是索引,x是值
a={'love':456} b={'baby':123} c={} for i in a: c[i]=a[i] for i in b: c[i]=b[i] #经测试,c最后为{'love': 456, 'baby': 123} #简化一下,**在python被称为unpacking(解包) a={'love':456} b={'baby':123} c={**a,**b}
s="succussful!" if score>90 else "fail"
#序列包括list、tuple、range…… name="Dai Quan" first_name,last_name=name.split()
#原先 f=open("test.txt","r") s=f.read() f.close() #用With后,省去了关闭语句 with open("test.txt","r") as f: s=f.read()