03-python--基础数据类型

一、int

  bit_length():查看整数的有效二进制长度

  i = 5

  i.bit_length()      # 3

二、bool

  bool str int 之间的转换

  int --> bool:非0为true,0为false

  bool --> int:true-->1,false-->0

  str --> bool:空字符串为false,其余为true

  bool --> str:没有意义

  int --> str:

  str --> int:只有字符串里全是数字能转,否则报错

三、str

# 字符串的索引与切片
s = "ABCDEFGHIJK"
s1 = s[0]        # 取指定索引字符
print(s1)
s2 = s[0:4]     # 取指定索引段内字符
print(s2)
s3 = s[-1]       # 取最后一位
print(s3)
s4 = s[0:]       # 取所有字符    
s5 = s[:]
print(s4, s5)
s6 = s[0:5:2]   # 按段切片,步长为2
print(s6)
s7 = s[4:0:-1]  # 倒着取
print(s7)
      
# 字符串操作
s = 'abCFGefgh'
print(s.capitalize())           # 首字母大写
print(s.upper())                # 全部大写
print(s.lower())                # 全部小写
print(s.swapcase())             # 大小写翻转
st = 'ac bv fg'
print(st.title())               # 非字母分隔首字母大写
print(st.center(20, '-'))       # 字符串居中对齐
print(s.expandtabs())           # 字符串中有	自动补齐
print(len(s), type(len(s)))     # 字符串元素产长度
print(s.startswith('b'))        # 字符串以什么开头,返回True or False
print(s.startswith('b', 4, 6))  # 上述加上切片
print(s.endswith('h'))          # 字符串以什么结尾,返回True or False
print(s.find('C'))              # 字符串是否包含某元素,返回索引,找不到返回-1。也可以切片
print(s.index('C'))             # 字符串是否包含某元素,返回索引,找不到报错。也可以切片
print(s.strip())                # 默认删除前后空格,可指定字符。lstrip,rstrip
print(s.count('a'))             # 查找指定字符串个数
print(st.split())               # 默认以空格分隔,可指定字符(字符串转换成列表)
# 字符串format
s1 = "i'm {} , age: {} , hobbie {} ".format('dfl', 32, 'bnd')
print(s1)
s2 = "i'm {0} , age: {1} , hobbie {0} ".format('dfl', 32, 'bnd')
print(s2)
s3 = "i'm {name} , age: {ages} , hobbie {name} ".format(name='dfl', ages=32, hobbies='bnd')
print(s3)
# 字符串替换
s = 'asdasdasdasdasd'
print(s.replace('a', 'b', 3))       # 替换,可指定次数
# 字符串 for 输出
s1 = 'asdqwedazxc'
for i in s1:
    print(i)
s2 = 'gfhelkjdflsdasdasd'
if 'dfl' in s2:
    print('yes')
# 字符串 join
s1 = 'alex'
s2 = '+'.join(s1)
print(s2, type(s2))
l1 = ['太白', '女神', '吴超']
# 前提:列表里面的元素必须都是str类型
s3 = ':'.join(l1)
print(s3)
# 字符串is系列判断字符
name = '123a'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成
print(name.isnumeric()) #只有数字
print(name.isdecimal()) #字符串只由十进制组成

 四、input

username = input('your name:  ')
password = input('your password:   ')
code = 'qwer'
your_code = input('your code:  ')
if your_code == code:
    if username == 'dfl' and password == '123':
        print('welcome')
    else:
        print('error username or password')
else:
    print('code wrong')
原文地址:https://www.cnblogs.com/Daspig/p/12591538.html