字符串
用单引号或双引号或三引号,引起来的对象就是字符串
s1 = 'abc'
s2 = "abc"
s3 = """abc"""
print(s1, s2, s3)
print(type(s1), type(s2), type(s3))
单双引号要错开使用
s4 = 'hello '"world"
print(s4)
三引号一般用于多行注释
'''
qqq
ddd
'''
转义符
s1 = 'hello \nworld'
filepath = 'D:\new.txt'
#方案一,在\n的前面加\
filepath1 = 'D:\\new.txt'
print(filepath1)
#方案二,在字符串的前面加一个r
filepath2 = r'D:\new.txt'
print(filepath2)
#方案三, 用/代替\
filepath3 = 'D:/new.txt'
print(filepath3)
字符串拼接
print('abc' + 'def')
print('abc''def')
print('a'*3)
字符串下表和切片
s = 'abcdefg'
print(s[0])
字符串的切片[开始位置:结束位置:步长],顾前不顾后
s = 'abcdefgddssdfghh'
print(s[2:5])
print(s[:3]) # 没有起始位置就代表从头开始
print(s[1:]) # 没有结束位置就代表切到字符串末尾
print(s[2:6:2]) #
print(s[:]) # 完整切片其实就是它自己本身
print(s[::-1])
列表
列表用[]表示,列表中的元素可以是任意对象,每个元素用逗号分隔
list1 = [1, 3, 'a', 3.14, 'abc']
print(list1[3])
print(list1[2:4])
list1_new = list1[:]
print(id(list1[:]))
print(id(list1_new))
列表的增删改
list3 = [1, 'a', '张三', 20, 'game']
a = list3.pop() # pop(),不指定参数,删除列表的最后一个元素
print(list3)
print(a)
list4 = [1, 'a', '张三', 20, 'game']
list4.remove('张三') # remove(值)
print(list4)
list5 = [1, 2, 3, 4, 'a']
del list5[-1] # del 关键字删除
print(list5)
元组
用()表示,元素之间逗号分隔,元素是不可变对象
t1 = (1, 3, 'a', 3.14, 'abc', [1, 2])
print(t1[0])
t1[-1][0] = 2
print(t1)
t1[0] = 3
print(t1)
字典
用{}定义,以键值对的方式出现,字典是可变对象,字典的键可以存放不可变对象,值存放任意对象;字典是无序的,键是唯一的
d1 = {
'a': 1, 'b': 2}
d2 = {
'b': 2, 'a': 1}
print(d1 == d2)
d3 = {
'a':1, 'b': 3}
print(d3['b']) # 字典取值 d['键']
d1 = {
1: 'a'}
d1['b'] = 2 # 新增
print(d1)
d1['b'] = 3 # 修改
print(d1)
d2 = {
'name':'张三', 'age': 20}
name = d2.pop('name') # 删除
print(name)
print(d2)
d2.clear() # 清空
print(d2)
json
json是一种很像字典的字符串,里面的元素用双引号,字典是单引号
p1 = {
'name': 'zhangsan'} # 字典
p2 = '{"name": "zhangsan"}' # json
print(p1, p2)
print(type(p1), type(p2))
import json
# 字典转json
res1 = json.dumps(p1)
print(res1, type(res1))
# json转字典
d1 = json.loads(p2)
print(d1, type(d1))
布尔表达式
使用比较运算符进行比较的式子,运算结果为布尔值,bool,它有两个值True(1) False(0)
print(True + True)
比较运算符<, >=, < ,<=,==,!=
print(1 == 2)
print(10 > 9)
print('a' > 'A')
and——并且,一假为假,全真为真
or——或者,一真为真,全假为假
not——非
in, not in
a = 1
b = 2
print(a > 1 and b > 1)
print(a >= 1 and b > 1)
print(a > 1 or b > 1)
print(not a > 1)
list1 = [100, 200, 300, [400, 500]]
print(100 in list1)
print(500 in list1)
not>and>or
print(