In [1]: # 格式化字符串
...: print('the age of %s is %d' % ('xiaoming',14))
the age of xiaoming is 14
In [2]: astr='the age of %s is %d' % ('xiaoming',14)
In [3]: astr
Out[3]: 'the age of xiaoming is 14'
In [4]: print('the age of {} is {}'.format('xiaoming',14))
the age of xiaoming is 14
In [5]: 'the age of {} is {}'.format('xiaoming',14)
Out[5]: 'the age of xiaoming is 14'
In [6]: # 重定向
...:
...: import sys
...:
...: print('write to standar error',file=sys.stderr)
...:
...:
write to standar error
In [7]: f=open('output.txt',mode='a')
...: print('write to file',file=f)
...: f.close()
...:
...:
In [8]: # 打印函数
...:
...: help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
In [9]: print(1,2)
1 2
In [10]: print((1,2))
(1, 2)
In [11]: for i in range(5):
...: print(i,i+1)
...:
0 1
1 2
2 3
3 4
4 5
In [12]: for i in range(5):
...: print(i,i+1,sep=',')
...:
0,1
1,2
2,3
3,4
4,5
In [13]: for i in range(5):
...: print(i,i+1,sep=',',end=',')
...:
0,1,1,2,2,3,3,4,4,5,
In [14]: 2*3,2**3
Out[14]: (6, 8)
In [15]: 1<2<3<4
Out[15]: True
In [16]: #字符串
...:
...: '123abc,'*3
Out[16]: '123abc,123abc,123abc,'
In [17]: # 字典
...:
...: adict={'name':'xiaoming','age':14}
...: adict.keys()
...:
...:
Out[17]: dict_keys(['name', 'age'])
In [18]: adict.items()
Out[18]: dict_items([('name', 'xiaoming'), ('age', 14)])
In [19]: # for ... else ...
...: for i in [1,2,2,1,1]:
...: if i==12:
...: print('found')
...: else:
...: print('not found')
...:
not found
In [20]: for i in [1,2,2,1,1]:
...: if i ==1:
...: print(1)
...: else:
...: print('no')
...:
1
1
1
no
In [21]: for i in [1,1,1,1,1]:
...: if i ==1:
...: print(1)
...: else:
...: print('no')
...:
1
1
1
1
1
no
In [22]: for i in [1,1,1,1,1]:
...: if i ==1:
...: print(1)
...: break
...: else:
...: print('no')
...:
1
In [23]: [i for i in range(10)]
Out[23]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [24]: [i for i in range(10) if i%3!=0]
Out[24]: [1, 2, 4, 5, 7, 8]
In [25]: {k+1:v*2 for k,v in {1:2,3:4}.items()}
Out[25]: {2: 4, 4: 8}
In [26]: # 引用调用,值传递
...: import random
...:
...: def random_append(alist):
...: alist.append(random.random())
...:
...: alist=[1,2,3]
...: random_append(alist)
...: alist
...:
...:
Out[26]: [1, 2, 3, 0.0028516098921210764]
Python3语言的特色用法
最新推荐文章于 2024-04-26 16:20:07 发布