数据类型-元组-字符串-布尔

例题引导:

把True变为False,把False变为True后输出:

参考答案:

print not True
print not False 

学习引导:

  • 数据类型-布尔
  • 数据类型-元组
  • 数据类型-字符串

bool布尔类型

布尔类型取值只有两种情况,表示真假值,即 yes or no

  • python 中布尔值使用常量True 和 False来表示;注意大小写
  • 比较运算符< > == 等返回的类型就是bool类型;
  • 布尔类型通常在 if (判断)和 while (循环)语句中应用

下面是一个简单的案例演示

print(True==1)
print(False==0)
print(2>1)
print(0>3)
'''
True
True
True
False
'''

小测试:

请列举布尔值是false的值:

数据类型-元组

和列表很相似,区别在于

  • 不可修改

  • 用小括号框

  • 其余用法基本一致

下面我们直接演示一些元组的方法

#索引、长度、切片、循环
a=[2,3,4,5,'32','你好']
a
#[2, 3, 4, 5, '32', '你好']
a[4]  #元组中第5个元素
#'32'
len(a)  #元组a的长度
#6
a[0:3]  #取该元组中第一个到第三个的值
#[2, 3, 4]

遍历元组

for i in a:
    print(i)
2
3
4
5
32
你好

查询判断

'32' in a  #判断字符串32是否在元组a中
#True
32 in a  #判断整数32是否在元组a中
#False

如果不可变的元组中包含可变的元素(例如列表),则元组可变

tuple_=(3,4,2,'元组',[3,4,'d','2'],'32')
tuple_
#(3, 4, 2, '元组', [3, 4, 'd', '2'], '32')
#更改数据会报错
tuple_[3]=1
tuple_
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-9-13fb7bda7784> in <module>
----> 1 tuple_[3]=1
      2 tuple_
TypeError: 'tuple' object does not support item assignment
#更改元组中的列表部分
tuple_[4][0]='数据'
tuple_
#(3, 4, 2, '元组', ['数据', 4, 'd', '2'], '32')

string字符串

  • 和列表操作类似
  • 切片 索引
  • 特点是不可变性

python中单引号和双引号使用完全相同。
使用三引号(‘’’或”””)可以指定一个多行字符串。

print('data science')

print("data science")

print('''this is data science
Learning together''')

print("""this is data science
Learning together""")
'''
data science
data science
this is data science
Learning together
this is data science
Learning together
'''
  • 转义符 ‘’:反斜杠可以用来转义,使用r可以让反斜杠不发生转义。
  • 如 r”data science \n”
  • 则\n会显示,并不是换行。
  • 按字面意义级联字符串,如”this “ “is “ “data science”会被自动转换为this is data science。

转义字符演示

print('data\nscience')  #表示换行

print(r'data\nscience')  #加r则无特殊意义,正常输出

print('this','is','DataScience')  #逐个输出字符串
'''
data
science
data\nscience
this is DataScience
'''

字符串可以用 ‘+’运算符连接在一起,用 ‘*’ 运算符重复。

str='DataScience'
print(str+'你好')  #连接两个字符串
print(str*5)  #打印该字符串5次
#DataScience你好
#DataScienceDataScienceDataScienceDataScienceDataScience

Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。

索引演示:

str='DataScience'
print(str[1])  #打印该字符串中第一个元素
print(str[2:-1])  #打印该字符串中第三个元素到倒数第二个元素
#a
#taScienc

Python中的字符串不能改变。

str='DataScience'
str[0]='s'
print(str[0])
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-31-f432ac1ed2d2> in <module>
      1 str='DataScience'
----> 2 str[0]='s'
      3 print(str[0])
TypeError: 'str' object does not support item assignment

Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
字符串的截取的语法格式如下:变量[头下标:尾下标:步长]

str='welcome to the DataScience'
print(str[0:13:2])
#wloet h

关于字符串的内容,后面有一节会详细讲解。

今天没有很多小练习,建议复习一下之前的学习内容。

评论