python学习笔记基础三

1,int.bit_length

i = 5
print(i.bit_length())
#int 转换成2进制后的长度
'''
            bit_length
1   0000 0001   1
2   0000 0010   2
3   0000 0011   3
4   0000 0100   3
5   0000 0101   3
'''

运行结果:

3

2,数据类型转换

#-*- encoding:utf-8 -*-
#int ---> str
i = 1
s = str(i)
#str --->int
s = '123'
i = int(s)
#int --->bool 只要是0就转换成False 非0就是True
i = 3
b = bool(i)
print(b)
#bool --->int
#True   1
#False  0
'''
#ps:while 死循环 while 1比while True 效率高。
while True:
    pass
while 1: 
    pass
'''
#str --->bool
#s = '' --->False
#s = '0' --->True
#非空字符串即是True,空字符串就是False
s1 = ''
if s1:
    pass
else:
    print('字符串为空')
s1 = '0'
if s1:
    print('字符串不为空')
else:
    pass

运行结果:

True
字符串为空
字符串不为空

3,字符串的索引与切片

#字符串的索引与切片
s = 'ABCDEFG'
#索引
s1 = s[0]
print(s1)
#BCD
s2 = s[1:4] # BCD
print(s2)
#取最后一位
s3 = s[-1]
print(s3)
#第一位到倒数第二位
s4 = s[0:-2]
print(s4)

运行结果:

A
BCD
G
ABCDE

补长:ABCDEFG取ACD

s = 'ABCEDFG'
s5 = s[0:5:2]
print(s5)

运行结果:

ACD

补充:倒着取

#倒着取
s = 'ABCDEFG' s6 = s[5:0:-2] print(s6)

运行结果:

FEB
原文地址:https://www.cnblogs.com/Dmail/p/11568067.html