python
字符串
#!/usr/bin/python3
str='123456789'
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始后的所有字符
print(str[1:5:2]) # 输出从第二个开始到第五个且每隔一个的字符(步长为2)
print(str * 2) # 输出字符串两次
print(str + '你好') # 连接字符串
print('------------------------------')
print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
end=””:
print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=””:
#!/usr/bin/python3
x="a"
y="b"
# 换行输出
print( x )
print( y )
print('---------')
# 不换行输出
print( x, end=" " )
print( y, end=" " )
print()
import 与 from…import
在 python 用 import 或者 from...import 来导入相应的模块。
将整个模块(somemodule)导入,格式为: import somemodule
从某个模块中导入某个函数,格式为: from somemodule import somefunction
从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc
将某个模块中的全部函数导入,格式为: from somemodule import *
数学函数
abs()返回数字的绝对值
fabs()返回数字的绝对值
fabs()函数只对浮点型跟整型数值有效
abs() 还可以运用在复数中
ceil()返回数字的上入整数
exp()返回x的指数e**x
floor(x) 返回数字的下舍整数
关键字end可以用于将结果输出到同一行,或者在输出的末尾添加不同的字符
# Fibonacci series: 斐波纳契数列
# 两个元素的总和确定了下一个数
a, b = 0, 1
while b < 1000:
print(b, end=',')
a, b = b, a+b
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
字典dict
字典中每个key用 : 分开,每个对之间用(,)分割
dict作为Python的关键字和内置函数
变量名不建议命名为dict
空字典
joey = {} #创建空字典
print(joey) #打印字典
print("Length:",len(joey)) #字典数量
print(type(joey)) #字典类型
{}
Length:0
<class 'dict'>
访问字典的值
joey = {'name': 'joey', 'age': '18', 'sex': 'male'}
print("joey = ",joey)
print(joey['name'])
print(joey['age'])
print(joey['sex'])
joey = {'name': 'joey', 'age': '18', 'sex': 'male'}
joey
18
male
修改字典
joey = {'name': 'joey', 'age': '18', 'sex': 'male'}
print("joey = ", joey)
joey['name'] = 'Eggy'
joey['age'] = 19
print("joey = ", joey)
joey = {'name': 'joey', 'age': '18', 'sex': 'male'}
joey = {'name': 'Eggy', 'age': 19, 'sex': 'male'}
删除字典元素
joey = {'name': 'joey', 'age': '18', 'sex': 'male'}
del joey['name'] #删除键'name'
print("joey = ", joey)
joey.clear() #清空字典
print("joey = ", joey)
del joey #删除字典
print("joey = ", joey)
joey = {'age': '18', 'sex': 'male'}
joey = {}
#引发异常,因为del后字典不再存在
Traceback (most recent call last):
File "D:\pythonProject1\main.py", line 10, in <module>
print("joey = ",joey)
NameError: name 'joey' is not defined
字典内置函数&方法
len(dict)计算字典元素个数,即键的总数
str(dict)输出字典,可以打印的字符串表示
type(variable)返回输入的变量类型,如果变量是字典就返回字典类型
元组
空元组
tup1 = ()
元组中只包含一个元素时,需要在元素后面添加逗号
tup1 = (50,)
访问元组
tup = (1, 2, 3, 4, 5, 6, 7 )
print("tup[1:5]: ", tup[1:5])
tup[1:5]: (2, 3, 4, 5)
修改元组
tup = (1, 2, 3, 4, 5, 6, 7 )
tup[0] = 10
删除元组
元组中的元素值不允许删除,但可以删出整个元组
tup = (1, 2, 3, 4, 5, 6, 7 )
del tup
元组截取
tup = (1, 2, 3, 4, 5, 6, 7 )
print(tup[3:])
(4, 5, 6, 7)
元组内置函数
len(tuple)计算元组元素个数
max(tuple)返回元组中元素最大值
min(tuple)返回元组中元素最小值
tuple(seq)将列表转换为元组
列表list
list = [1, 2, 3, 4, 5 ]
更新列表
list = [1, 2, 3, 4, 5 ]
list.append(6)
[1, 2, 3, 4, 5, 6]
删除列表元素
list = [1, 2, 3, 4, 5 ]
del list[2]
[1,2,4,5]
for
for num in range(10,20): # 迭代 10 到 20 之间的数字
for i in range(2,num): # 根据因子迭代
if num%i == 0: # 确定第一个因子
j=num/i # 计算第二个因子
print ('%d 等于 %d * %d' % (num,i,j))
break # 跳出当前循环
else: # 循环的 else 部分
print ('%d 是一个质数' % num)
10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数
冒个泡
arays = [1,8,2,6,3,9,4]
for i in range(len(arays)):
for j in range(i+1):
if arays[i] < arays[j]:
# 实现连个变量的互换
arays[i],arays[j] = arays[j],arays[i]
print arays
range
range( start , stop )
默认从0开始
>>>range(10)
#range(10)等价于range(0,10)
>>>[0,1,2,3,4,5,6,7,8,9]
>>>range(1,10)
>>>[1,2,3,4,5,6,7,8,9]
x = 'Joey'
for i in range(len(x)):
print(x[i],end=" ")
J o e y
pass
pass 是空语句,是为了保持程序结构的完整性
pass 不做任何事情,一般用做占位语句
空函数在Python2.x版本中pass是必须的
在Python3.x的时候pass可以写或不写
def function():
pass
集合
a={'1','2','3','4','1'}#or a=set('12341')
b={'1','6','5','2','7'}
print(a)
#输出无重复且无序
{'1', '2', '4', '3'}
print('1' in a)
True
print(a-b)#a特有的元素
{'4','3'}
print(a|b)#ab所有元素,无重复
{'6', '3', '1', '2', '7', '5', '4'}
print(a&b)#ab共有的元素
{'1', '2'}
print(a^b)#不同时包含的元素
{'6', '7', '4', '3', '5'}
#a.add(x)讲元素x添加到a中,如果已存在,则不进行操作
#a.discard(x)删除元素
a.add('9')
{'2', '1', '3', '9', '4'}
#.update(x)也可以添加元素,而且可以应用到列表,字典,元组
创建一个含有一个元素的集合
my_set = set(('joey',))
{'joey'}
创建一个含有多个元素的集合
my_set = set(('joey','eggy'))
{'joey','eggy'}
非必要不写成set(‘joey’)
函数
def functionname( parameters ):
"函数_文档字符串"
function_suite
return [expression]
chr()
chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符
chr(i)
- i — 可以是10进制也可以是16进制的形式的数字
- 返回值是当前整数对应的 ASCII 字符
encode()
encode() 方法使用指定的编码对字符串进行编码。如果未指定编码,则将使用 UTF-8
语法
string.encode(encoding=encoding, errors=errors)
参数 | 描述 |
---|---|
encoding | 可选。字符串。规定要使用的编码。默认是 UTF-8。 |
errors | 可选。字符串。规定错误方法。合法值是: ‘backslashreplace’ – 使用反斜杠代替无法编码的字符 ‘ignore’ – 忽略无法编码的字符 ‘namereplace’ – 用解释字符的文本替换字符’strict’ – 默认值,失败时引发错误 ‘replace’ – 用问号替换字符 ‘xmlcharrefreplace’ – 用 xml 字符替换字符 |
randint(a,b)
生成一个在a和b直接的随机数(包含ab)
randint()被定义在random模组里
import random
a = random.randint(0,10)
print(a)
#output:0
#output:2
#output:7
ord()
返回ASCII值
print(ord('A'))
#output:6
libnum库
-
libnum.s2n(s):字符串转换为数字
import libnum s = "ab12" print(libnum.s2n(s)) result: 1633825074
-
libnum.n2s(n):数字转换为字符串
import libnum n = 1633825074 print(libnum.n2s(n)) result: ab12
-
libnum.s2b(s):字符串转换为二进制字符串
import libnum s = "ab12" print(libnum.s2b(s)) result: 01100001011000100011000100110010
-
libnum.b2s(b):二进制字符串转换为字符串
import libnum b = "01100001011000100011000100110010" print(libnum.b2s(b)) result: ab12
-
libnum.primes(n):返回不大于n的素数列表
import libnum print(libnum.primes(19)) result: [2, 3, 5, 7, 11, 13, 17, 19]
-
libnum.generate_prime(n):产生长度为n位的伪素数
import libnum print(libnum.generate_prime(10)) result: 1021
-
libnum.modular.invmod(e,m):返回e模m的逆元
import libnum print(libnum.modular.invmod(5,24)) #(e*m) result: 5
python的rsa库的使用
(22条消息) python的rsa库的使用_梅花14的博客-CSDN博客_python rsa
1、rsa算法
详细解释我们这里不做详细解释,自行搜索,理解起来也不难。
2、rsa库的使用
注意这里不是使用的pycryto
,仅仅使用了rsa
,安装也很简单pip install rsa
。
2.1 生成pubkey和privkey
import rsa
(pubkey, privkey) = rsa.newkeys(512) # 512这个数字表示可以加密的字符串长度,可以是1024,4096等等,
(pubkey, privkey) = rsa.newkeys(512, poolsize=8) # 使用多进程加速生成
123
不过数字越大生成的速度越慢,下面给出一个简单的对比
2.2 从文件中读取公钥或者私钥
with open('private.pem', mode='rb') as privatefile:
keydata = privatefile.read()
privkey = rsa.PrivateKey.load_pkcs1(keydata)
123
2.3 加密数据
加密数据使用pubkey
,解密数据使用privkey
。
message = 'hello Bob!'.encode('utf8')
# 加密数据
crypto = rsa.encrypt(message, pubkey)
# 解密数据
message = rsa.decrypt(crypto, privkey)
1234567
我们在2.1中生成的公钥和私钥可以用来加密的数据长度只有512bits,只有64个字节,其实还不到64个字节,还有11个字节被用作别用(具体的话会在下面给出链接,可以自行查看原文)。
那么问题来了,怎么加密大数据文件呢,来看下面的方法。
import rsa
from rsa.bigfile import *
(pub_key, priv_key) = rsa.newkeys(512)
# 加密数据
with open('inputfile', 'rb') as infile, open('outputfile', 'wb') as outfile:
encrypt_bigfile(infile, outfile, pub_key)
# 解密数组
with open('inputfile', 'rb') as infile, open('outputfile', 'wb') as outfile:
decrypt_bigfile(infile, outfile, priv_key)
1234567891011
2.4 数字签名
签名使用privkey,验证使用pubkey。刚好和加密相反。
对字符串的签名和验证
(pubkey, privkey) = rsa.newkeys(512)
message = 'Go left at the blue tree'
# 签名
signature = rsa.sign(message, privkey, 'SHA-1')
# 验证
rsa.verify(message, signature, pubkey)
123456
对文件的签名和验证
# 签名
with open('somefile', 'rb') as msgfile:
signature = rsa.sign(msgfile, privkey, 'SHA-1')
# 验证
with open('somefile', 'rb') as msgfile:
rsa.verify(msgfile, signature, pubkey)
1234567
3、总结
我们常说,非对称加密使用pubkey
加密数据,privkey
解密数据。
服务器公开pubkey
,让我们来向服务器发送数据,那么如果服务器向我们发送数据怎么办呢?这个问题还没搞明白,有路过的大神还望不吝赐教。