Python学习第003天

一.内容概述:今天主要学习了python的基础数据类型int,str,bool的一些操作,重点是str类型的一些操作。且看下文具体内容。

二.int的操作

对于一个数字除了运算几乎没有其他的操作,所以int的第一个操作就是我们常见的数学运算: + - * / % //
int的第二个操作是:

bit_lenght() # bit二进制 lenght长度 这个方法是返回一个数字的二进制的长度。
如:
n1 = 8  # 二进制为:1000
print(n1.bit_length()) # 打印出的结果是4
三.bool的操作
对于bool数据类型的操作主要是数据类型的转换。
bool-->int True--1 False--0   # bool转换成int类型,True对应1,False对应0.
ss = False
print(type(ss)) # <class 'bool'>
ss1 = int(ss) # 转换成int类型
print(ss1, type(ss1)) # 0 <class 'int'>
ss2 = True
ss3 = int(ss2)
print(ss3, type(ss3)) # 1 <class 'int'>
实际中,
bool中空和0为False,非空为True
False: 0,'',[],{},set(),tuple(),None(真空)
举例:
print(bool('你好'))  # True
print(bool(1)) # True
print(bool(-1)) # True
print(bool(5.3)) # True
print(bool()) # False
print(bool([])) # False
print(bool({})) # False
print(bool(None)) # False
print(bool(0)) # False
三.str的操作
1.索引
字符串中每个字符的位置顺序;
索引从0开始. 程序员数数从0开始
s[索引] 获取到字符串s中的索引位置的数据。
s = '文能提笔安天下'
print(s[3]) # 笔
2.切片
s[start: end: step]
从start开始到end结束。 但是取不到end. 每step个取一个
s1 = '周末我喜欢读书看电影和户外运动'
print(s1[1:5]) # 顾头不顾尾
rint(s1[:7]) # 从头开始取到7
print(s1[3:]) # 从3开始取到末尾
print(s1[:]) # 从头取到尾
3. 字符串的一些主要操作方法
1).upper() 全部转化成大写字母

name4 = 'shawn'
print(name4.upper()) # 打印结果是SHAWN
 2).strip() 去掉左右两段的空白(空格,\n, \t)

s14 = ' s hawn '
s15 = s14.strip()
print(s15)
# 打印结果是s hawn
 3).replace(old, new) 字符串替换

s20 = 'hello world, good evening'
s21 = s20.replace('o', '*')
print(s21) # 打印结果是hell* w*rld, g**d evening
 4).split() 切割. 得到的结果是一个列表.

s22 = "追风筝的人_看见_明朝那些事_大秦帝国_成功心理学"
s23 = s22.split('_')
print(s23) # 打印的结果是['追风筝的人','看见','明朝那些事','大秦帝国','成功心理学']
 5).startswith() 判断是否以xxx开头

s30 = 'allen_like_reading'
s31 = s30.startswith('allen')
print(s31) # 打印结果是True
 6).find() 查找。如果找到了。 返回索引。如果找不到返回-1

s36 = 'shawn_is_a_good_man'
s37 = s36.find('o')
print(s37) # 12
print(s36.find('y')) # -1
 7).len() 内置函数,求字符串长度
s46 = 'ajfoshgih'
print(len(s46)) # 9
4. 迭代
for 变量 in 可迭代对象:
循环体
s49 = "今天周五了。 深圳有什么好玩的呢? 我爱学习, 我爱工作。 我爱代码"
for c in s49:
if c == '爱':
break
print(c)
else:
print('over')

 
 
 
 


 
 
 
 
 
 
 
 
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/Hsiyi/p/9822113.html
今日推荐