字面量
以变量或常量给出的原始数据
字面量类型:
数值型
字符型
布尔型
字面量集合:列表,元组,字典,集合
特殊字面量:None
字面量插值
将变量,常量以及表达式插入的一种技术,他可以避免字符串拼接的问题
3种方法
1 格式化
%的用法
>>> name = "lili" >>> print("my name is %s" %name) my name is lili
>>> name = "lili" >>> print("my name is %s" %name) my name is lili >>> age = 10 >>> print("my name is %s,my age is %d" %(name,age)) my name is lili,my age is 10 >>>
>>> name = "lili" >>> print("my name is %s" %name) my name is lili >>> age = 10 >>> print("my name is %s,my age is %d" %(name,age)) my name is lili,my age is 10 >>> print("my name is %s,my age is %d,num is %f" %(name,age,3.34444)) my name is lili,my age is 10,num is 3.344440 >>>
>>> print("my name is %s,my age is %d,num is %.2f" %(name,age,3.34444)) my name is lili,my age is 10,num is 3.34 >>>
name = "lili" age = 90 list1 = [1,2,3,4] dic1 = {"a":"fo","b":"c"} print("my name is {0},age is {1}".format(name,age)) print("my name is {1},age is {0} {1}{0}{0}".format(name,age)) print("my list is {},my dic is {}".format(list1,dic1))
2 format()方法
用法:str.format()可以将
字符串
列表
字段
name = "lili" print("my name is {}".format(name))
name = "lili" age = 90 print("my name is {},age is {}".format(name,age))
name = "lili" age = 90 print("my name is {0},age is {1}".format(name,age)) print("my name is {1},age is {0}".format(name,age))
输出结果
D:py estvenvScriptspython.exe "D:/py/test/拉勾-第三阶段/模块7 输入与输出.py" my name is lili,age is 90 my name is 90,age is lili
列表的解包,需要加*
# name = ["lili","tom","jerry"] # print("we name is {}、{} and {}".format(*name))
#字典的解包,需要加** #用法print("my name is {key值},my age is {key值}".format(**dic)) dic = {"name":"lili","age":44} print("my name is {name},my age is {age}".format(**dic))
3 F-strings 字符串格式化机制
使用方法:f'{变量名}
注意:大括号里面可以是表达式或者函数
大括号内不能转移,不能使用
list = ["lili","tom","jerry"] name = "lili" dic = {"name":"lili","age":44} print(f"my name is {name},my list is {list},my dic is {dic}")
输出结果
D:py estvenvScriptspython.exe "D:/py/test/拉勾-第三阶段/模块7 输入与输出.py" my name is lili,my list is ['lili', 'tom', 'jerry'],my dic is {'name': 'lili', 'age': 44}
#可以插入表达式
list = ["lili","tom","jerry"] name = "abcdef" dic = {"name":"lili","age":44} print(f"my name is {name.upper()},my list is {list},my dic is {dic}")
如果表达式有:之类的特殊字符,需要加一个()
print(f"resule is {(lambda x : x+1)(2)}")
输出结果
resule is 3
文件的读取
操作步骤
1 打开文件,获取文件描述符
2 操作文件描述符读,写
3 关闭文件
注意:
文件读写错操作完成后,应该及时关闭
open()
with 语句块,可以将文件打开之后,操作完毕,自动关闭这个文件
图片的读取需要使用rb,读取二进制的格式
正常的文本,可以使用rt,也就是它的默认格式即可
with open("date.txt") as f: print(f.readlines())
输出结果
D:py estvenvScriptspython.exe D:/py/test/拉勾-第三阶段/文件的读写.py ['1 ', 'd ', '4 ', 'g ', 'v ', 'g ', 'hdhddkkdkddldkd']
with open("date.txt") as f: while True: line = f.readline() if line: print(line) else: break
json格式转化
import json dic = { "name":["jerry","ladddd"], "age":20 } print(type(dic)) dic2 = json.dumps(dic)# dumps讲json转换成字符串的格式 print(dic2) print(type(dic2)) dic3 = json.loads(dic2)#loads讲字符串转换成dict形式 print(type(dic3))