学习python有几个月了,但是一直没有总结过,后来看别人代码的时候发现有很多知识漏洞。于是想到了记笔记这个方法,写这样的一份学习笔记是一个梳理的过程,可以让我们更好得记住那些盲点,让自己的python基础更扎实。
- 布尔值方面
名字很高大上,其实就是True、False两个值
例如:
a = "方平文"
b = "苹"
c = "方"
print(b in a)
print(c in a)
结果是:
False
True
- 原来int()方法后面可以带参数
num = "0011"
v = int(num, base=16)
#将num基于16进制转换成数字类型(int是代表数字类型,即为整型)
print(v)
结果是:17
- bit_lenth()方法,显示当前数字用二进制表示是会占多少位
我们知道二级制是这样对应的:
1 1
2 10
5 101
age = 5
r = age.bit_length()
print(r)
这结果一定是:3
- 字符串变换大小写与字符串占格
test = "alex"
v = test.capitalize() #首字母大写
v1 = v.casefold() #首字母变小写
v2 = test.center(20,"*") #将test占20个空格且把test放在中间,周围用"*"补齐
v3 = test.ljust(20,"*") #将test中的内容放左边
v4 = test.rjust(20,"*") #将test中的内容放右边
v5 = test.upper() #全部变为大写
print(v)
print(v1)
print(v2)
print(v3)
print(v4)
print(v5)
结果是:
Alex
alex
alex
alex****************
****************alex
ALEX
- 字符串的去除空格与某个字符
test = ' alex '
v = test.lstrip() #去除左边的空格和\t,\n
v1 = test.rstrip() #去除右边的空格和\t,\n
v2 = test.strip() #两边都去除
v3 = 'linghaifenghai.cn'.strip('hai.cn') #去除字符串中的'hai.cn'(从右往左数)
print(v)
print(v1)
print(v2)
print(v3)
结果是:
- 数某字符或子串在字符串中出现的次数
test = "alexalexr"
v = test.count('e',2,8) #从第2个字符到第8个字符,数e在test中出现的次数
v1 = test.endswith('r') #判断是否以字符r结尾
v2 = test.startswith('r') #判断是否以字符r开始
v3 = test.find('ex',5,8) #在5<= 和 <8之间是否有ex字符
print(v)
print(v1)
print(v2)
print(v3)
结果是:
2
True
False
6
Ps:此处v3的运行结果是6,说明find()方法返回了子串’ex’在test中的索引位置,而且是从右往左数
- 字符串的格式化(另外还有一个format_map,用法类似)
# format可以修改{}中的值
test = "I am {name}, age {a}"
v = test.format(name='alex',a=19)
v1 = "if i {} rain, {} would call {} the course.".format('were to','we','off')
print(v)
print(v1)
结果是:
I am alex, age 19
if i were to rain, we would call off the course.
- 判断是否存在某字符
test = "utasf890_"
v = test.isalnum()
v1 = test.isalpha() #判断是否全是字母
v2 = test.isdigit() #判断是否是数字字符串
v3 = test.isprintable() #是否存在不可显示的字符,如\n,\t等转义字符
print(v)
print(v1)
print(v2)
print(v3)
结果是:
False
False
False
True
- 字符串标题化
test = "if it were to rain, we would call off the course."
v = test.title() #将字符串转化成标题样式,即首字母大写
v1 = test.istitle() #判断是否是标题
v2 = v.istitle()
print(v)
print(v2)
print(v2)
结果是:
If It Were To Rain, We Would Call Off The Course.
True
True
- join()方法
#用某个字符将字符串拼接起来
test = "你是风儿我是沙"
v = '-'.join(test) #用'-'号将test分割
print(v)
结果是:
你-是-风-儿-我-是-沙
- 字符串分割与切片
test = "ajfkdsahfskhsadfss"
v = test.partition('s') #用's'将test分割成多个字符串
v1 = test.split('s') #用's'尽可能多得将test分割
v2 = test.split('s',3) #匹配三次's',分割三次,切成4节子串
v3 = test[0:2] #切片,获取0<= <2的范围内的字符
print(v)
print(v1)
print(v2)
print(v3)
结果是:
(‘ajfkd’, ‘s’, ‘ahfskhsadfss’)
[‘ajfkd’, ‘ahf’, ‘kh’, ‘adf’, ‘’, ‘’]
[‘ajfkd’, ‘ahf’, ‘kh’, ‘adfss’]
aj
- **len()与replace()**方法
test = "alexalexalex"
a = len(test) #获取字符串长度(2.7版本中一个中文字符是3个字节)
v = test.replace("ex",'bbb') #将test中的'ex'都替换成'bbb'
print(a)
print(v)
结果是:
12
albbbalbbbalbbb
- 字符串可迭代可循环
test = "愿这个世界与你温柔以待"
for item in test:
print(item)
break
结果只会出现一次"愿",因为第一次循环结束就break跳出了
- 既输出索引又输出对应字符
test = input(">>>")
for item in range(0,len(test)):
print(item,test[item])
输入:love
结果是:
0 l
1 o
2 v
3 e
该方法类似于C语言中char类型数组下标的用法