蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

字符串:转义、格式化与完整方法表

按码点、编码和返回值核对字符串,保留旧写法并明确Python3迁移。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

创建、索引和不可变

单/双引号和三引号可建立str,单字符仍是str。正负索引与左闭右开切片分别保留;修改文本通常创建或取得另一个字符串并重新绑定,不能对原槽位赋值。两张原图均展示索引和切片关系,重绑定更新由本站代码单独验证;本站示例使用自己的品牌文案。

str是Unicode文本,bytes是字节序列;Python2的str是字节而非保证ASCII,Python2的Unicode内部实现也不能简单概括为统一固定16位。Python3的u前缀只作兼容标记,encode返回bytes、bytes.decode返回str。

转义、raw和终端行为

表格保留行尾反斜杠、\\、\'、\"、\a、\b、\000、\n、\v、\t、\r、\f、八进制和十六进制以及未识别转义。字符值与终端如何显示是两回事:\000是U+0000,不是空字符串;响铃和退格不保证每个终端都会产生同样声音或画面。

\r回到当前行开头的显示行为依输出终端而定,不会自动清除剩余字符;写入文件仍保存回车码点。百分比进度可结合end=""与flush=True,刷新标准流也不等于每个接收端立即刷新屏幕。

\x需要两位十六进制数,八进制最多三位。未识别转义在本轮3.12中可能给SyntaxWarning,不能永远当无警告普通文本;用双反斜杠或合适raw写法。raw仍受引号与末尾奇数反斜杠规则约束,三引号也仍解释普通转义,并非完全所见即所得。

连接、查找与旧百分号格式

+、*、[]、切片、in/not in、r/R和%逐项保留;字符串成员可以是子串,不限单字符。%与str.format以及f-string各有用途,不把旧格式无说明删去。

%c可接受Unicode码点而非仅ASCII,%u在Python3等同%d而非强制无符号,负数仍可带负号;%p不是Python3字符串支持的格式符,保留错误说明与实际ValueError。对象身份可单独用id的诊断表示,但不承诺物理地址。

%o/%x/%X、%f/%e/%E/%g/%G、宽度/精度*、左右对齐、符号、空格、#、零填充、%%和映射键全部保留。#的八进制前缀是0o;%g按有效数字和指数范围选形式,不只是一句两种格式简写。

现代格式与多行工程文本

str.format可通过位置和名称插入;f-string自Python3.6可用,可计算固定代码中的表达式,3.8增加表达式=调试形式。格式宽度与.2f等限制与值的实际数值精度不是一回事,格式化不会改原数值。

三引号可存多行HTML或SQL,但字符串插入不自动完成HTML转义或SQL参数绑定。本站实际在内存SQLite建表、参数写入与读取,用html.escape处理页面中的自有文字;原页HTML片段里的脚本只在内部读取,绝不执行。

40项方法和函数逐个对照

参考表保留全部40个来源入口,包括其中的bytes.decode以及len/max/min这些并非str实例方法的项。每行提供输入、返回类型和限制,再补充casefold、removeprefix/removesuffix等现代处理方式,不能用少数常用方法代替整表。

join要求每项已是str,不会自动对整数调用str。split的实际签名是sep=None、maxsplit=-1;空sep失败,默认空白拆分与显式空格拆分不同。strip/lstrip/rstrip的chars是字符集合,不是完整前后缀。

str.translate在Python3使用Unicode码点映射,可映射到整数、str或None;旧256字符表与deletechars参数属于不同旧/字节接口,不照搬到str。find/rfind失败返回-1,index/rindex失败ValueError,空内容、范围和替换次数分别核对。

Unicode判别、对齐与练习

isdigit/isnumeric/isdecimal是不同Unicode集合,空串通常不通过;上标2、分数、汉字数值与十进制数字不能混为一类。大小写判别需至少一个有大小写的字符,isalpha也不只限英文和中文。

expandtabs按下一个制表位置补空格,不是每个tab固定变8空格;len是码点数而非UTF8字节数或用户感知字符数。title/swapcase等依Unicode规则,不保证符合每种自然语言排版或来回完全恢复。

练习时分别预测值、类型、原字符串是否变化和异常。真实终端声音/控制效果与命令行捕获的字符另记状态;方法调用成功和表格数量也不等于所有来源链接实例均已完成语义验收。

转义字符

写法字符含义条件
\ + 物理换行忽略字符串中的续行换行不是保留字面反斜杠
\\反斜杠U+005C值长度1
\'单引号值长度1
\"双引号值长度1
\aBEL U+0007声音由终端决定
\bBS U+0008捕获字符与终端光标效果分开
\000NUL U+0000不是空字符串
\nLF U+000A换行字符
\vVT U+000B纵向制表控制
\tHT U+0009制表位置不是固定8空格
\rCR U+000D不自动清除该行剩余内容
\fFF U+000C换页效果依接收端
\ooo最多3位八进制过大转义有版本警告
\xhh两位十六进制少位或非hex为语法错误
\other未识别转义3.12可能SyntaxWarning;不当通用推荐

字符串操作

符号含义
+连接str
*按整数重复
[]索引一个字符
[:]切片
in子串检测
not in子串不包含
r/R原始字面量前缀,仍受引号语法约束
%旧式格式化

百分号格式符

格式用途限制
%c单字符或Unicode整数码点超范围OverflowError,不限ASCII
%sstr转换表示可显示任意对象
%d十进制整数形式不是任意文本的int解析
%uPython3中等同%d不强制无符号,负数仍带负号
%o八进制形式负数按符号输出
%x小写十六进制整数输入
%X大写十六进制整数输入
%f定点形式精度是小数位
%e小写指数形式精度为尾数小数位
%E大写指数形式指数标记E
%g一般形式按精度和指数选定点/指数
%G大写一般形式大写指数和特殊值
%pPython3不支持保留历史错误项,实际ValueError

百分号辅助语法

语法作用形式
*从元组读取宽度或精度%*.*f
-左对齐%-5s
+显示正号%+d
空格正数前留空格% d
#进制等替代表示%#o产生0o前缀
0符号后补零%05d
%%一个百分号不消耗独立值
(name)从映射取值%(site)s
m.n最小宽度和精度%8.2f,宽度不是截断上限

完整40项入口

入口输入返回限制/纠错
capitalize()无参str首字符标题化且其余小写,不只是首字变大写
center(width,fillchar=" ")整数宽度/单字符填充str不足宽度不截断;多字符fillchar TypeError
count(sub,start=0,end)子串及范围int非重叠计数,空sub与范围另核
bytes.decode(encoding,errors)bytes及编码策略str不是str.decode;错误UnicodeDecodeError/LookupError
encode(encoding,errors)str及编码策略bytes默认strict,失败具体为UnicodeEncodeError等
endswith(suffix,start,end)后缀str或tuplebool范围影响匹配
expandtabs(tabsize=8)整数制表宽度str补到下个制表位置,非每个固定8空格
find(sub,start,end)子串与范围int失败-1;结果是原字符串索引
index(sub,start,end)子串与范围int失败ValueError
isalnum()非空Unicode文本bool每项均字母或数字
isalpha()非空Unicode文本boolUnicode字母不限英文中文
isdigit()非空数字类bool含上标等,不等同十进制
islower()至少一个有大小写字符bool所有有大小写字符为小写
isnumeric()非空Unicode数值类bool包括某些分数,不代表int可解析
isspace()非空空白类bool不是只检查ASCII空格
istitle()文本bool按Unicode标题规则,空串False
isupper()至少一个有大小写字符bool有大小写字符全部大写
join(iterable)每项都是strstr非str元素TypeError,不自动转换
len(text)文本int内置函数;计码点,不是字节/字形
ljust(width,fillchar=" ")宽度/单字符str左对齐,不截断
lower()无参strUnicode小写转换
lstrip(chars=None)字符集合str不是整体前缀删除
str.maketrans(x,y,z)映射或等长字符串/删除串dict建立码点映射;可删除、扩展
max(text)非空文本长度1的str内置;按字符比较,不是自然语言排序
min(text)非空文本长度1的str空输入ValueError
replace(old,new,count=-1)两个str及最大次数strcount0不替换,旧str不变
rfind(sub,start,end)子串与范围int从右找,返回正向索引;失败-1
rindex(sub,start,end)子串与范围int失败ValueError
rjust(width,fillchar=" ")宽度/单字符str右对齐,不截断
rstrip(chars=None)字符集合str不是整体后缀删除
split(sep=None,maxsplit=-1)分隔符/最多拆分次数list[str]空sep ValueError;默认空白语义不同
splitlines(keepends=False)是否保留边界字符list[str]支持多种行边界;末尾换行不额外添空行
startswith(prefix,start,end)前缀str或tuplebool范围影响匹配
strip(chars=None)两侧字符集合str不是截掉一个完整子串
swapcase()无参strUnicode大小写交换;不保证可逆
title()无参str按字符类别划词,撇号词可能非自然语言预期
translate(table)码点索引映射strstr可映射整数/str/None;无deletechars参数
upper()无参strUnicode大写转换,长度可能变化
zfill(width)总宽度str零补在正负号后
isdecimal()非空Unicode十进制字符bool比isdigit/isnumeric更窄

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 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,'&lt;Learning &amp; Sky&gt;')
    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 环境

当前源码 SHA256:1e101f5e6826257c02a4eae79067b43f49f795fa9d151d0d0b769687f3b2d5e8

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据