Python 基础函数01
Table of Contents
1 3.X中print()
在python3.2:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
sep表示输出之间的符号,end表示整个输出的结束符。
>>> print('hello', 'world')
hello world
>>> print('hello', 'world', sep='\n')
hello #Because sep is \n, this is a new line.
world
>>> print('hello', 'world', end=' ')
hello world >>> #Because end is ' ', so this is no newline.
NewLearn01Start:
>>> import sys
>>> sys.stdout = open('data.txt', 'a')
>>> print('helloworld')
print默认的file=sys.stdout,现把sys.stdout重设为已打开的文件对象(采用附加模式),之后任何print打印语句都会把文件追加至data.txt文件中。
>>> import sys
>>> temp = sys.stdout
>>> sys.stdout = open('data.txt', 'a')
>>> print("can't be seen")
>>> sys.stdout.close()
>>> sys.stdout = temp
>>> print('can be seen')
can be seen
先保存sys.stdout至temp中,为sys.stdou重新赋值,再关闭sys.stdou,再重新恢复sys.stdout。
NewLearnEnd01:
2 integers:
2.1 ord()
ord('字符') #返回ASCII码
3 str()
4 repr()
5 //除
6 print 默认回车
7 math.trunc()
去除浮点后面的 因为版本问题:在2.6中 3/2=>1,而在3.0中 3/2 =>1.5。为避免版本引起的问题,可以用math.trunc().math.trunc(3/2)=>1
8 math.floor()
>>> math.floor(2.5) 2.0 >>> math.floor(-2.5) -3.0
9 oct() hex() bin()
把10进制整数转化成8 16 2进制字符串
2.6版本中8进制前面加0,3.0版本中前面加0o
>>> oct(64), hex(64), bin(64)
('0100', '0x40', '0b1000000')
10 int()
int(x[, base]) -> integer
把一个数字的字符串变换为整数,其中base指定指定x的进制。
>>> int('64'), int('100', 8), int('40', 16), int('1000000', 2)
(64, 64, 64, 64)
>>> int('0x40', 16), int('0b1000000', 2) #与上面等价
(64, 64)
11 eval()
12 bitlength()
#以二进制查询表示一个数字的什所需的位数 >>> (256).bit_length() 9 >>> len(bin(256)) - 2 9
13 math.pi math.e math.sin() math.sqrt() math.pow() pow() abs() min() max()
python中有三种方法可以计算平方根: import math math.sqrt(144) pow(144, .5) 144 ** .5
pow(x, y[, z]) -> number 通常是两个参数,若三个则表示 (x ** y) % z
14 random module
14.1 random.random()
随机生成0-1之间的小数
14.2 random.randint(a, b)
随机生成a-b之间的娄 >>> random.randint(1, 10) 5
14.3 random.choice(self, seq)
随机从序列中挑选 >>> random.choice(['a', 'b', 'c']) 'c'
Date: 2011-08-01 19:14:46 CST
HTML generated by org-mode 6.33x in emacs 23
作者:visayafan
出处:http://www.cnblogs.com/visayafan/
本博客文章欢迎转载,转载时请注意标明出处。


浙公网安备 33010602011771号