1.字符串(运算支持加和乘)
- a= 'zjh'
- a="zjh"
- a='''zjh'''
- a="""zjh """
以上三种引号形式均可,引号内为字符串,引号必须成对出现。
字符串相加是把两个字符串拼接起来
字符串相乘是输入相乘的次数
举例:
>>> n1='1' >>> n2='2' >>> n3=n1+n2 >>> print(n3) 12 >>> print(n1*10) 1111111111
方法举例:
- expandtabs()通过断句实现制表等
test = '用户名 班级 年龄 张三 一年级 20 李四 一年级 20 王五 一年级 20 ' print(test.expandtabs(20)) 输出结果: 用户名 班级 年龄 张三 一年级 20 李四 一年级 20 王五 一年级 20
- isalnum():确实是否都是数字和字母
#结果为false,因为包含特殊字符 test = '123abc+_*/' print(test.isalnum()) #结果为true test = '123abc' print(test.isalnum())
- isalpha():判断是否都是字母,汉字
- isdecimal()、isdigit()、isme判断是否是数字以及两者区别
test = '②' v1 = test.isdecimal() #特殊字符的数字不支持 v2 = test.isdigit() #特殊字符的数字支持 print(v1,v2) #结果输出: False True
test = '二' v1 = test.isdecimal() #特殊字符的数字不支持 v2 = test.isdigit() #特殊字符的数字支持 v3 = test.isnumeric() #支持中文的数字 print(v1,v2,v3) #结果输出 false false True
- isidentifier()判断变量名是否合法
print( "if".isidentifier() ) print( "def".isidentifier() ) print( "class".isidentifier() ) print( "_a".isidentifier() ) print( "中国123a".isidentifier() ) print( "123".isidentifier() ) print( "3a".isidentifier() ) print( "".isidentifier() ) #结果 True True True True True False False False
- isprintable()判断是否全部可显示输出的内容
# 不是可显示输出的内容,所有结果是false test = 'abcd 1234' v = test.isprintable() print(v)
- center()、ljust()、rjust() 空白填充
test = 'zjh' v = test.center(20,'*') v1 = test.ljust(20,'*') v2 = test.rjust(20,'*') print(v,' ',v1,' ',v2) #结果输出 ********zjh********* zjh***************** *****************zjh
- join字符串中插入字符
#两种方式 test = 'woainizhongguo' v = '_' r = v.join(test) r1 = '***'.join(test) print(r,' ',r1) #结果输出 w_o_a_i_n_i_z_h_o_n_g_g_u_o w***o***a***i***n***i***z***h***o***n***g***g***u***o
- 对应关系替换
test = 'wo ai ni zhong abc' v = str.maketrans('abcdef','123456') new_test =test.translate(v) print(new_test) #结果输出 wo 1i ni zhong 123
- 分割partition(),split()
# 永远只能分割为三份,不能选择分割个数,并且被分割的字符可以取到 test = 'wo,shi,zhong,guo,ren' v = test.partition(',',) print(v) #可以分割所有,并且可以根据个数分割,被分割的字符可以取到 test = 'wo,shi,zhong,guo,ren' v = test.split(',') print(v)
2.数字(加减乘除次方,求余数)
>>> 2**4 次方 16 >>> 39%8 求余 7
>>> 39//8 取商
4
常用方法:
- 字符串转换
#将a的字符串强制转换为数字类型 a = '123' b = int(a)
- 查看类型
#查看a的类型,实际结果为type a = '123' b = int(a) print(type(a))
- 当前数字以二进制表示
#将字符串num转换成2进制的数字形式,结果为3
#base=8为8进制,base=16为16进制 num = '0011' v = int(num,base=2) print(v)
- -bit_length
#表示21这个数字,至少用5个二进制位表示 age = 21 r = age.bit_length() print(r)
3.布尔值真和假,true和false