格式化输出
三种方法:% , f"{a}" , "{}".format(a)
tpl = "i am {}, age {}, {}"
r = tpl.format("yangge", 18, 'yangge')
tpl = "i am {0}, age {1}, really {0}"
print(tpl.format("xiguatian", 18))
tpl = "i am {name}, age {age}, really {name}"
print(tpl.format(name="xiguatian", age=18))
tpl = "i am {0[0]}, age {0[1]}, really {1[2]}"
print(tpl.format([1, 2, 3], [11, 22, 33]))
tpl = "i am {:s}, age {:d}, money {:f}"
print(tpl.format("seven", 18, 88888.1))
tpl = "i am {name:s}, age {age:d}"
tpl.format(name="xiguatian", age=18)
tpl = "i am {name:s}, age {age:d}"
tpl.format(**{"name": "xiguatian", "age": 18})
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X},\
{0:.2%}"
print(tpl.format(15))
f"{}" 方法
f "{2 * 37}"
f"{to_lowercase(name)} is strong." #中可以写个函数
f"{self.first_name} {self.last_name} is {self.age}." #使用类对象
f"Hi {name}. "
f"You are a {profession}. "
f"You were in {msg}."
与
f"Hi {name}. "
"You are a {profession}. "
"You were in {msg}."
等价
详细参考连接shark
python操作mysql
首先在安装pymysql
pip3 install pymysql
创建表
import pymysql
# 创建连接
conn = pymysql.connect(host='172.16.153.10',
port=3306,
user='root',
passwd='123',
db='shark_db',
charset='utf8mb4')
# 获取游标对象
cursor = conn.cursor()
# 定义 sql 语句
create_table_sql = """create table t1
(id int auto_increment primary key,
name varchar(10) not null,
age int not null)"""
# 执行 sql 语句
cursor.execute(create_table_sql)
# 提交更改
conn.commit()
# 关闭游标对象
cursor.close()
# 关闭连接对象
conn.close()
插入数据
#一次插入一条数据, 并且使用变量占位符
insert_data_sql = "insert into t1(name, age) values(%s, %s);"
row = cursor.execute(insert_data_sql, ('shark', 18))
定义插入数据的语句
many_sql = "insert into t1 (name, age) values(%s, %s)"
一次插入多条数据
row = cursor.executemany(many_sql, [('shark1', 18),('xiguatian', 20),('qf', 8)])
conn.commit()
cursor.close()
conn.close()
查询
#定义一个查询语句
query_sql = "select id,name,age from t1 where name=%s;"
#执行查询语句,并且返回得到结果的行数
row_nums = cursor.execute(query_sql, ('shark2'))
#获取到数据结果集具有迭代器的特性:
#1. 可以通过索引取值,可以切片
#2. 结果集中的数据每次取出一条就少一条
详细参考链接shark
网友评论