"""蓝色天空网 mbsky.com: all forty entries, escape codepoints and format branches."""
from pathlib import Path
import sys,ast,warnings,io,html,sqlite3,contextlib,unicodedata
sys.path.insert(0,str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
c=Checks()
def main():
original='mbsky.com';c.eq('index/slice',(original[0],original[-1],original[2:5]),('m','m','sky'));updated=original[:2]+'blue.com';c.eq('new string text',updated,'mbblue.com');c.eq('old remains',original,'mbsky.com')
c.eq('string operations',(original+'!', 'sky'*2,'sky'in original,'html'not in original),('mbsky.com!','skysky',True,True))
c.eq('single char still str',type(original[0]).__name__,'str')
escapes=[('backslash','\\',92),('single quote',"'",39),('double quote','"',34),('bell','\a',7),('backspace','\b',8),('NUL','\000',0),('newline','\n',10),('vertical tab','\v',11),('horizontal tab','\t',9),('carriage return','\r',13),('form feed','\f',12),('octal','\101',65),('hex','\x41',65)]
for name,value,want in escapes:c.eq('escape codepoint '+name,ord(value),want)
fixture='"ab'+chr(92)+'\n'+'cd"';c.eq('explicit physical continuation',ast.literal_eval(fixture),'abcd');c.eq('NUL not empty',len('\000'),1)
c.eq('raw lower/upper',(r'\n',R'\n'),('\\n','\\n'));c.eq('raw length',len(r'\n'),2)
c.raises('raw odd trailing slash',SyntaxError,lambda:compile('value=r"path'+chr(92)+'"','<owned-raw>','exec'))
c.raises('hex requires two digits',SyntaxError,lambda:compile('value="'+chr(92)+'x4"','<owned-hex>','exec'))
with warnings.catch_warnings(record=True)as observed_warnings:
warnings.simplefilter('always');namespace={};exec(compile('value="'+chr(92)+'q"','<owned-unrecognized-escape>','exec'),namespace)
c.eq('unknown escape actual retained',namespace['value'],'\\q');c.eq('3.12 unknown escape warning',[w.category.__name__ for w in observed_warnings],['SyntaxWarning'])
captured=io.StringIO()
for value in [0,50,100]:print(f'\r蓝色天空网 {value:3}%',end='',file=captured,flush=True)
print(file=captured);c.eq('progress actual carriage returns',captured.getvalue().count('\r'),3);c.eq('progress final percent and newline',captured.getvalue().endswith('100%\n'),True)
percent_specs=[('%c',0x5929,'天'),('%s','mbsky.com','mbsky.com'),('%d',12,'12'),('%u',-12,'-12'),('%o',15,'17'),('%x',255,'ff'),('%X',255,'FF'),('%.2f',1.25,'1.25'),('%.1e',125.0,'1.2e+02'),('%.1E',125.0,'1.2E+02'),('%.3g',1250.0,'1.25e+03'),('%.3G',1250.0,'1.25E+03')]
for format_spec,value,want in percent_specs:c.eq('percent '+format_spec,format_spec%value,want)
c.raises('%p unsupported',ValueError,lambda:'%p'%1);c.eq('star width precision','%*.*f'%(6,2,1.25),' 1.25');c.eq('left align','%-5s'%'sky','sky ');c.eq('plus sign','%+d'%7,'+7');c.eq('space sign','% d'%7,' 7');c.eq('alternate oct/hex',('%#o'%15,'%#x'%15),('0o17','0xf'));c.eq('zeros after sign','%05d'%-7,'-0007');c.eq('literal percent','%d%%'%70,'70%');c.eq('mapping format','%(site)s'%{'site':'mbsky.com'},'mbsky.com');c.eq('minimum width not truncation','%3s'%'mbsky','mbsky')
number=4;c.eq('str format','{} · {}'.format('蓝色天空网','mbsky.com'),'蓝色天空网 · mbsky.com');c.eq('f expression',f'{number+1}','5');c.eq('f debug expression',f'{number+1=}','number+1=5');c.eq('literal f braces',f'{{{number}}}','{4}')
multiline="""第一行
第二行\t内容
""";c.eq('triple retained newline',multiline.count('\n'),2)
escaped=html.escape('<Learning & Sky>');c.eq('HTML explicitly escaped',escaped,'<Learning & Sky>')
with contextlib.closing(sqlite3.connect(':memory:'))as connection:
connection.execute('''CREATE TABLE lessons (
label TEXT,
amount INTEGER
)''')
connection.execute('INSERT INTO lessons VALUES (?, ?)',("Sky's lesson",3))
c.eq('multiline SQL and parameter binding',connection.execute('SELECT label,amount FROM lessons').fetchone(),("Sky's lesson",3))
# Each of the forty original entry names has its own actual observation.
c.eq('01 capitalize','sKY'.capitalize(),'Sky')
c.eq('02 center','sky'.center(7,'-'),'--sky--');c.raises('center fillchar one char',TypeError,lambda:'sky'.center(8,'--'))
c.eq('03 count','aaaa'.count('aa'),2);c.eq('count bounded','abab'.count('ab',1,4),1);c.eq('count empty substring','abc'.count(''),4)
c.eq('04 bytes.decode','天空'.encode('utf8').decode('utf8'),'天空');c.eq('str has no decode',hasattr('sky','decode'),False);c.raises('bad decode',UnicodeDecodeError,lambda:b'\xff'.decode('utf8'))
c.eq('05 encode','天空'.encode('utf8'),b'\xe5\xa4\xa9\xe7\xa9\xba');c.raises('encode exact error',UnicodeEncodeError,lambda:'天'.encode('ascii'))
c.eq('06 endswith','mbsky.com'.endswith(('.net','.com')),True);c.eq('endswith slice','abcxyz'.endswith('bc',0,3),True)
c.eq('07 expandtabs next column','ab\tc'.expandtabs(4),'ab c');c.eq('expandtabs reset line','a\tb\nab\tc'.expandtabs(4),'a b\nab c')
c.eq('08 find','abcabc'.find('bc',2),4);c.eq('find missing','sky'.find('x'),-1)
c.eq('09 index','abcabc'.index('bc'),1);c.raises('index missing',ValueError,lambda:'sky'.index('x'))
c.eq('10 isalnum','天A2'.isalnum(),True)
c.eq('11 isalpha','天πA'.isalpha(),True)
c.eq('12 isdigit','²'.isdigit(),True);c.eq('digit not decimal','²'.isdecimal(),False)
c.eq('13 islower','abc123'.islower(),True);c.eq('uncased text not lower','天空'.islower(),False)
c.eq('14 isnumeric','¼'.isnumeric(),True);c.eq('numeric not digit','¼'.isdigit(),False)
c.eq('15 isspace',' \t\n'.isspace(),True)
c.eq('16 istitle','Blue Sky'.istitle(),True)
c.eq('17 isupper','ABC123'.isupper(),True);c.eq('uncased text not upper','天空'.isupper(),False)
c.eq('18 join','/'.join(['HTML','CSS']), 'HTML/CSS');c.raises('join no implicit str',TypeError,lambda:'/'.join(['HTML',3]))
c.eq('19 len codepoints',len('天空'),2);c.eq('UTF8 bytes separate',len('天空'.encode('utf8')),6);c.eq('combining sequence len',len('e\u0301'),2);c.eq('NFC different codepoint count',len(unicodedata.normalize('NFC','e\u0301')),1)
c.eq('20 ljust','sky'.ljust(5,'.'),'sky..')
c.eq('21 lower','SKY'.lower(),'sky')
c.eq('22 lstrip character set','abcabcsky'.lstrip('abc'),'sky');c.eq('prefix is different','abcabcsky'.removeprefix('abc'),'abcsky')
c.eq('23 maketrans','abc'.translate(str.maketrans('ab','xy','c')),'xy')
c.eq('24 max',max('azb'),'z');c.raises('max empty',ValueError,lambda:max(''))
c.eq('25 min',min('azb'),'a');c.raises('min empty',ValueError,lambda:min(''))
c.eq('26 replace','aaaa'.replace('a','b',2),'bbaa');c.eq('replace zero','sky'.replace('s','S',0),'sky')
c.eq('27 rfind','abcabc'.rfind('bc'),4);c.eq('rfind missing','sky'.rfind('x'),-1)
c.eq('28 rindex','abcabc'.rindex('bc'),4);c.raises('rindex missing',ValueError,lambda:'sky'.rindex('x'))
c.eq('29 rjust','sky'.rjust(5,'.'),'..sky')
c.eq('30 rstrip set','skyabcabc'.rstrip('abc'),'sky');c.eq('suffix differs','skyabcabc'.removesuffix('abc'),'skyabc')
c.eq('31 split defaults','a b'.split(),['a','b']);c.eq('split explicit spaces','a b'.split(' '),['a','','b']);c.eq('split maxsplit','a,b,c'.split(',',1),['a','b,c']);c.raises('split empty separator',ValueError,lambda:'abc'.split(''))
c.eq('32 splitlines','a\r\nb\n'.splitlines(),['a','b']);c.eq('splitlines keepends','a\r\nb\n'.splitlines(True),['a\r\n','b\n'])
c.eq('33 startswith','mbsky.com'.startswith(('mb','blue')),True)
c.eq('34 strip','abskyba'.strip('ab'),'sky')
c.eq('35 swapcase','sKy'.swapcase(),'SkY')
c.eq('36 title',"they're".title(),"They'Re")
c.eq('37 translate Unicode','abc'.translate(str.maketrans({'a':'AA','b':None})),'AAc');c.raises('old str translate deletechars invalid',TypeError,lambda:'abc'.translate({},'b'))
c.eq('38 upper Unicode can expand','ß'.upper(),'SS');c.eq('casefold addition','Straße'.casefold(),'strasse')
c.eq('39 zfill','-42'.zfill(5),'-0042')
c.eq('40 isdecimal','١٢'.isdecimal(),True)
for method in ['isalnum','isalpha','isdigit','isnumeric','isspace','islower','isupper','istitle','isdecimal']:c.eq('empty false '+method,getattr('',method)(),False)
c.finish('python3-string',physical_continuation_fixture=fixture,preserve_format_fields=['physical_continuation_fixture'],terminal_sound_and_visual_cursor_effect='not tested; codepoints and captured stream only',unknown_escape_warnings=[dict(category=w.category.__name__,message=str(w.message))for w in observed_warnings],captured_progress=captured.getvalue())
if __name__=='__main__':main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-string.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-string.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip