失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Python数据类型(二)文本类型-str

Python数据类型(二)文本类型-str

时间:2023-03-13 18:34:20

相关推荐

Python数据类型(二)文本类型-str

Python中处理文本数据使用由Unicode编码构成的不可变序列字符串—str对象。字符串表达形式如下:

.单引号 ‘This article describes information about str object’

.双引号 “This article describes information about str object”

.三重引号 ‘’‘ This article describes information about str object’’’

使用三重引号的字符串可以跨越多行,并且所有的空字符串都包含在字符串值中。

str类型同样是不可变类型,除了上面三种显式构建方式之外,也同样有构建函数进行构建

字符串构建

构建函数:

>>> str(b'Zoot!')"b'Zoot!'"

字符串访问

可以直接通过index的方式访问字符串中的字符,如字符串s = ‘abcdfdeff’, s[0] = ‘a’, s[0:3]=’abc’, s[0:3]也可以写成s[:3],代表从0个位置开始,取第3个字符之前的字节,第一个数字代表从第几个字符开始,:后面代表取到第几个字节(最后一个字节的字符不包含在内)。

因为不存在单独的字符类型,对字符串做索引操作的时候会产生长度为1的字符串,即s[0] == s[0:1]

字面值

字符串的字面值定义如下:

stringliteral ::= [stringprefix](shortstring | longstring)stringprefix ::= "r" | "u" | "R" | "U" | "f" | "F"| "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"shortstring::= "'" shortstringitem* "'" | '"' shortstringitem* '"'longstring::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'shortstringitem ::= shortstringchar | stringescapeseqlongstringitem ::= longstringchar | stringescapeseqshortstringchar ::= <any source character except "\" or newline or the quote>longstringchar ::= <any source character except "\">stringescapeseq ::= "\" <any source character>

bytesliteral ::= bytesprefix(shortbytes | longbytes)bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"shortbytes::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'longbytes::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'shortbytesitem ::= shortbyteschar | bytesescapeseqlongbytesitem ::= longbyteschar | bytesescapeseqshortbyteschar ::= <any ASCII character except "\" or newline or the quote>longbyteschar ::= <any ASCII character except "\">bytesescapeseq ::= "\" <any ASCII character>

第一种字面值是描述str类型,第二种字面值是描述bytes类型。

如果字符串前面带有’b’或’B’ 等bytesprefix类型,则生成的是bytes类型;如果字符串前面带有’r’,’u’则生成的是str类型;如果字符串前面带有’r’或’R’,则代表字符串不会进行转义。

为了与 Python 2 系列的向下兼容,再次允许字符串字面值使用u前缀。 它对字符串字面值的含义没有影响,并且不能与r前缀同时出现。

转义序列&行边界

字面值拼接

多个相邻的字符串或字节串字面值 (以空白符分隔),所用的引号可以彼此不同,其含义等同于全部拼接为一体。因此,"hello" 'world'等同于"helloworld"。此特性可以减少反斜杠的使用,以方便地将很长的字符串分成多个物理行,甚至每部分字符串还可分别加注释

字符串常量

字符串定义的常量有:

字符串格式化

一般字符格式化

string 模块中提供来一般字符格式化转换类,利用转换类中的转换函数可以格式化字符串。格式转换类为string模块中的Formatter类,Formatter类中的转换函数有:

格式化字符串语法

str.format()方法和Formatter类为格式化字符串提供相同的语法,但是仍有一些不同。

格式字符串包含由大括号包围的“替换字段”{替换值}。不包含在大括号中的任何内容都被视为文本,它将原封不动地复制到输出中。如果需要在文本中包含大括号字符,则可以通过加倍对其进行转义: 。在一些比较正式的语法中,替换字段可以以字段名开始,该字段名指定要格式化其值并插入到输出中而不是替换字段中的对象。字段“名称”后面可选跟一个转换字段,转换字段前面加一个感叹号“!”和格式“spec”,前面是冒号“:”。它们为替换值指定非默认格式。

字段“名称”本身以数字或关键字的参数开头。如果是数字,则表示位置参数;如果是关键字,则表示命名关键字参数。如果格式字符串中的数字arg_名称按顺序是0、1、2,…,则可以全部省略,数字0、1、2,…)将自动按该顺序插入。因为arg_名称不是用引号分隔的,所以不能在格式字符串中指定任意字典键(例如字符串“10”或“:-]”)。参数名后面可以跟任意数量的索引或属性表达式。表单的表达式“.name”使用getattr()选择命名属性,而表单的表达式“[index]”使用getitem()进行索引查找。

3.1版本中 str.format()可以省略位置参数说明符,因此’{}{}’.format(a,b)等同于“0 1”格式 ‘{0} {1}’.format(a, b)。 3.5版本之后格式化程序可以省略位置参数说明符。

转换字段在格式化前导致类型强制。通常,格式化值的工作是由值本身的format()方法完成。但是,在某些情况下,需要强制将类型格式化为字符串,从而覆盖其自己的格式化定义。通过在调用format()之前将值转换为字符串,可以绕过正常的格式化逻辑。例如'!s'会先调用str()函数进行转换 ,'!r'会先调用repr()函数进行转换以及!a会先调用ascii()函数进行转换。

format_spec字段包含如何显示值的说明,包括字段宽度、对齐方式、填充、小数精度等详细信息。每个值类型都可以定义自己的Mini-Language或格式说明。format_spec字段还可以包含嵌套的替换字段。这些嵌套的替换字段可能包含字段名、转换标志和格式规范,但不允许进行更深层次的嵌套。format_spec中的替换字段在格式化format_spec字符串之前被替换。这样造成可以允许动态指定值的格式。

通过位置访问参数进行替换:

>>> '{0},{1},{2}'.format('a','b','c')'a,b,c'>>> '{},{},{}'.format('a','b','c')'a,b,c'>>> '{2},{1},{0}'.format('a','b','c')'c,b,a'>>> '{},{},{}'.format(*'abc')'a,b,c'>>> '{2},{1},{0}'.format(*'abc')'c,b,a'>>> '{0},{1},{0}'.format('abra', 'cad')'abra,cad,abra'

通过name访问参数进行替换:

>>> 'Coordinates: {latitude},{longitude}'.format(latitude='37.24N', longitude='-115.81W')'Coordinates: 37.24N,-115.81W'>>> "I'm a girl and my job is {jobname}".format(jobname='Data Analysistic')"I'm a girl and my job is Data Analysistic"

通过属性访问参数进行替换:

>>> c = 3-5j>>> ('复数{0}是由实部{0.real} 和 虚部{0.imag}构成').format(c)'复数(3-5j)是由实部3.0 和 虚部-5.0构成'>>> class Point:def __init__(self, x, y):self.x, self.y = x, ydef __str__(self):return 'Point({self.x}, {self.y})'.format(self=self)>>> str(Point(4,2))'Point(4, 2)'

通过items访问参数进行替换:

>>> coord = (3,4)>>> 'X:{0[0]}; Y:{0[1]}'.format(coord)'X:3; Y:4'

替换%s和%r:

>>> "repr() shows quotes:{!r}; str() doesn't:{!s}".format('test1','test2')"repr() shows quotes:'test1'; str() doesn't:test2"

对齐文本并指定宽度:

>>> '{:<30}'.format('left aligned')'left aligned '>>> '{:>30}'.format('right aligned')' right aligned'>>> '{:^30}'.format('centered')' centered '>>> '{:*^30}'.format('centered')'***********centered***********'

替换%+f, %-f, % f以及指定符号:

>>> '{:<30}'.format('left aligned')'left aligned '>>> '{:>30}'.format('right aligned')' right aligned'>>> '{:^30}'.format('centered')' centered '>>> '{:*^30}'.format('centered')'***********centered***********'

替换%x,%o以及将值转换为不同的基数:

>>> "int:{0:d}; hex:{0:x}; oct:{0:o}; bin:{0:b}".format(42)'int:42; hex:2a; oct:52; bin:101010'>>> "int:{0:d}; hex:{0:#x}; oct:{0:#o}; bin:{0:#b}".format(42)'int:42; hex:0x2a; oct:0o52; bin:0b101010'>>>

使用逗号,作为千位分隔符:

>>> '{:,}'.format(1234567890)'1,234,567,890'>>>

百分数形式替换:

>>> points = 19>>> total = 22>>> 'Correct answers:{:.2%}'.format(points/total)'Correct answers:86.36%'

特殊类型格式转换:

>>> import datetime>>> d = datetime.datetime(,5,4,21,54,16)>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)'-05-04 21:54:16'

嵌套参数和更复杂的示例:

>>> for align, text in zip('<^>', ['left', 'center', 'right']):'{0:{fill}{align}16}'.format(text, fill=align, align=align)'left<<<<<<<<<<<<''^^^^^center^^^^^''>>>>>>>>>>>right'>>> octets = [192,168,0,1]>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)'C0A80001'>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)'C0A80001'>>> int(_, 16)3232235521>>> width = 5>>> for num in range(5, 12):for base in 'dXob':print('{0:{width}{base}}'.format(num, base=base, width=width), end='')print()5 5 5 1016 6 6 1107 7 7 1118 8 10 10009 9 11 100110 A 12 101011 B 13 1011>>>

格式化字符Mini-Language

格式化符号

格式化旗标

格式化类型

模板字符串

模板字符串提供来更简单的字符串替换形式,这样做重要的一点是国际化(i18n),较简单的语法和功能比Python其它内置字符串格式化更容易链接编译。

模板字符串规则

模板字符串支持基于$的替换,使用以下规则:

. $$ is an escape; it is replaced with a single $

.$idenfifier 匹配字典中的名为’idenfifier’的key。默认情况下,’identifier’仅限于以下划线或ASCII字母开头的任何不区分大小写的ASCII字母数字字符串(包括下划线), \$ 字符后的第一个非标识字符代表终止字符

.${identifier} 和 \$identifier 含义相同。当有效的标识字符跟在占位符之后但不是占位符的一部分(如\${noun}ification)的时候,必须采用\${identifier}的写法

字符串中出现的任何其他$都将导致引发ValueError。

木板字符串函数

string模块提供了Temple类执行以上规则,Temple类的方法有:

>>> from string import Template>>> s = Template('$who likes $what')>>> s.substitute(who='tim', what='running')'tim likes running'>>> d = dict(who='tim')>>>#制造KeyError>>> Template('Give $who $100').substitute()Traceback (most recent call last):File "<pyshell#33>", line 1, in <module>Template('Give $who $100').substitute()File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/string.py", line 130, in substitutereturn self.pattern.sub(convert, self.template)File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/string.py", line 123, in convertreturn str(mapping[named])KeyError: 'who'>>>#制造valueError>>> Template('Give $who $100').substitute(d)Traceback (most recent call last):File "<pyshell#34>", line 1, in <module>Template('Give $who $100').substitute(d)File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/string.py", line 130, in substitutereturn self.pattern.sub(convert, self.template)File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/string.py", line 127, in convertself._invalid(mo)File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/string.py", line 103, in _invalid(lineno, colno))ValueError: Invalid placeholder in string: line 1, col 11>>>#制造keyError>>> Template('$who likes $what').substitute(d)Traceback (most recent call last):File "<pyshell#35>", line 1, in <module>Template('$who likes $what').substitute(d)File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/string.py", line 130, in substitutereturn self.pattern.sub(convert, self.template)File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/string.py", line 123, in convertreturn str(mapping[named])KeyError: 'what'>>>#用safe_substitute函数避免Error>>> Template('$who likes $what').safe_substitute(d)'tim likes $what'

模板字符串高级用法

高级用法

可以派生模板的子类,以自定义占位符语法、分隔符或用于分析模板字符串的整个正则表达式。为此,可以重写这些类属性:

delimiter– 描述引入分隔符的占位符的文本字符串,默认值为$。注意,这不能是正则表达式,如果想要传入正则表达式,需要根据具体的规则在此字符串上调用re.escape()。

idpattern–描述无效占位符的正则表达式(括号将根据需要自动添加)。默认值是正则表达式(?-i:[_a-zA-Z][_a-zA-Z0-9]*)

flags–正则表达式标志,在编译期间将正则表达式转换为实际应用规则时被使用。默认值是re.VERBOSE。值得注意的是re.VERBOSE无论如何都会被添加到标志中,所以自定义的ID模式必须符合详细的正则表达式规则。

或者,可以通过重写类属性模式来提供整个正则表达式模式。这么做的前提是该值必须是具有四个捕获组组成的正则表达式对象, 捕获组与给出的规则以及无效的占位符规则相对应:

escaped– 该捕获组与默认模式中的转义序列(例如$$)匹配

named– 该捕获组与无空格的占位符名称匹配,并且不能包含分隔符

braced– 该捕获组与括号内的占位符名称匹配,不能包含分隔符或括号

invalid– 该捕获组与任何其他分隔符模式(通常是单个分隔符)匹配,它应该出现在正则表达式的最后一个

字符串方法

>>> string = 'string synatx custom string formatting'>>> string.capitalize()'String synatx custom string formatting'>>> string = string.capitalize()>>> print (string)String synatx custom string formatting>>> string = string.casefold()>>> print (string)string synatx custom string formatting>>> string.center(15, '*')'string synatx custom string formatting'>>> string.center(50, '*')'******string synatx custom string formatting******'>>> string.count('a', 0, 30)1>>> string.endswith('.com', 0)False>>> string.endswith('.com')False>>> '01\t012\t0123\t01234'.expandtabs()'01013 01234'>>> '01\t012\t0123\t01234'.expandtabs(5)'01 012 0123 01234'>>> string.find('f')28>>> 'f' in stringTrue>>> 'The sum of 4 + 5 is {0}'.format(4+5)'The sum of 4 + 5 is 9'>>> class Default(dict):def __missing__(self, key):return key>>> '{name} was born in {country}'.format_map(Default(name='Joy'))'Joy was born in country'>>> '{name} was born in {country}'.format_map(Default(name='Joy', country='Chinese')) 'Joy was born in Chinese'>>> string.isalnum()False>>> print (string) string synatx custom string formatting>>> string.isalpha() False>>> string.isdecimal() False>>> string.isdigit() False>>> string.isidentifier()False>>> string.islower()True>>> string.isnumeric() False>>> string.isprintable() True>>> string.isspace()False>>> string.istitle()False>>> string.isupper() False>>> string.join(['len', 'type'])'lenstring synatx custom string formattingtype'>>> ' '.join(['red','blue','green'])'red blue green'>>> string.ljust(50, '*') 'string synatx custom string formatting************'>>> string.partition('syn')('string ', 'syn', 'atx custom string formatting')>>> string.replace('s', 'S', 2) 'String Synatx custom string formatting'>>> string.rfind('syn') 7>>> string.rindex('syn') 7>>> string.rjust(50, '-')'------------string synatx custom string formatting'>>> string.rsplit()['string', 'synatx', 'custom', 'string', 'formatting']>>> string.rstrip() 'string synatx custom string formatting'>>> string.split()['string', 'synatx', 'custom', 'string', 'formatting']>>> string.splitlines() ['string synatx custom string formatting']>>> string.startswith('str') True>>> string.strip()'string synatx custom string formatting'>>> string.swapcase()'STRING SYNATX CUSTOM STRING FORMATTING'>>> string.title() 'String Synatx Custom String Formatting'>>> string.upper() 'STRING SYNATX CUSTOM STRING FORMATTING'>>> string.zfill(50)'000000000000string synatx custom string formatting'

如果觉得《Python数据类型(二)文本类型-str》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。