Python day2 part1:字符串编码

本文介绍了计算机中常用的字符串编码方式,包括ASCII、Unicode及UTF-8,并详细讲解了Python中字符串的编码转换方法,同时提供了字符串格式化的两种实用方式。

字符串编码方式主要有两种:ASCII码、Unicode码和UTF-8码

Unicode和UTF-8码支持汉字

UTF-8码是可变长的,UTF-8中英语字符通常是1个字节,而汉字通常为3个字节,比Unicode更加节约

  • 在计算机中

 内存、记事本里面使用Unicode编码,在文件或者传输途中使用UTF-8编码

  • 在网页中

 服务器里面是Unicode,而网页上提供给浏览
器的是UTF-8

1.字符串相关函数

a.      字符转化

         ord变汉字或英语字符为整数表示

   chr将整数表示换回字符

print(ord('A'))
print(ord('字'))
print(chr(65))
print(chr(25991))
结果:
65
23383
A
文
b.    字符串转化

 encode()可以将字符串变为指定形式的编码,decode()反之

 字符串与encode()和decode()之间使用.连接

 ()中间可以使用大写也可以使用小写,ascii与ASCII、utf-8与UTF-8都行

print('hello world'.encode('ascii'))
print('北京航空航天大学'.encode('utf-8'))
print('北京航空航天大学'.encode('UTF-8'))
print(b'hello world'.decode())
print(b'\xe5\x8c\x97\xe4\xba\xac\xe8\x88\xaa\xe7\xa9\xba\xe8\x88\xaa\xe5\xa4\xa9\xe5\xa4\xa7\xe5\xad\xa6'.decode())
b'hello world'
b'\xe5\x8c\x97\xe4\xba\xac\xe8\x88\xaa\xe7\xa9\xba\xe8\x88\xaa\xe5\xa4\xa9\xe5\xa4\xa7\xe5\xad\xa6'
b'\xe5\x8c\x97\xe4\xba\xac\xe8\x88\xaa\xe7\xa9\xba\xe8\x88\xaa\xe5\xa4\xa9\xe5\xa4\xa7\xe5\xad\xa6'
hello world
北京航空航天大学


2.格式化

a.旧式方法使用%连接

print('hello %s your final score is %lf'%('li ming',3.5))
C:\pythontest>python 1.py
hello li ming your final score is 3.500000
b.使用format()

format()将会依次替换{0} {1}所代表的值

print('hello {0} your final score is {1:.1f}'.format('li ming',3.5))
格式控制较为特殊,比较麻烦,但也比较强大

'{} {} {}'.format('a', 'b', 'c')





 

def fetch_data_from_db(self): """从数据库中读取数据,最多取50条,不足则全部取出""" today = datetime.now().strftime("%Y%m%d") conn = sqlite3.connect("schedule_log.db") cursor_FC= self.conn.cursor() cursor_FC.execute("SELECT name FROM sqlite_master WHERE type='table';") all_tables = [row[0] for row in cursor_FC.fetchall()] table_pattern = re.compile(r'^FClog_\d{8}$') matched_tables = [tbl for tbl in all_tables if table_pattern.match(tbl)] # 按日期倒序排序 def extract_date(table_name): date_str = table_name.split('_')[1] # 提取日期字符串 return datetime.strptime(date_str, "%Y%m%d") matched_tables.sort(key=extract_date, reverse=True) data = [] limit = 50 for table in matched_tables: if len(data) >= limit: break query = f"SELECT * FROM `{table}`" cursor_FC.execute(query) rows = cursor_FC.fetchall() if not rows: continue columns = [desc[0] for desc in cursor_FC.description] for row in rows: data.append(columns) if len(data) >= limit: break conn.close() print(data) def parse_time_with_mmdd(time_str, base_year=2025): time_str = time_str.strip() date_part, time_part = time_str.split(") ") mmdd = date_part[1:] # 去掉 '(' month = int(mmdd[:2]) day = int(mmdd[2:]) hour, minute, second = map(int, time_part.split(":")) return datetime(year=base_year, month=month, day=day, hour=hour, minute=minute, second=second) def calculate_intervals_strict(data): result = {} for row in data: train_name = row[1] time_strings = row[2:] # 所有时间字段 parsed_times = [parse_time_with_mmdd(t) for t in time_strings] # 解析时间 intervals = [] # 计算间隔 for i in range(1, len(parsed_times)): delta = (parsed_times[i] - parsed_times[i - 1]).total_seconds() / 60 intervals.append(round(delta, 2)) result[train_name] = intervals return result intervals_dict = calculate_intervals_strict(data) print(intervals_dict) for train, intervals in intervals_dict.items(): print(f"{train}: {intervals}")
最新发布
08-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值