字符串

字符串
字符串是不可变的。因此所有的元素赋值和切片赋值都是非法的。
设置字符串的格式:
将值转换为字符串并设置其格式。字符串格式设置运算符:百分号(%)。指定要设置其格式的值时,可使用单个值(如字符串或数字),可使用元组(若设置多个值的格式),还可以使用字典。
>>>format="hello,%s.%s enough for ya?"
>>>value=('world','hot')
>>>format % value --->'hello,world.hot enough for ya?'
注:%s称为转换说明符,指出要将值插入什么地方,s表示将值视为字符串进行格式设置。如果指定的值不是字符串,将使用str将其转换为字符串。
>>>from string import Template
>>>tmpl=Template("hello,$who! $what enough for ya?")
>>>tmpl.substitute(who="Mars",what="Dusty")
--->'hello,Mars! Dusty enough for ya?'
注:包含等号的参数称为关键字参数。可将关键字参数视为一种向命名替换字段提供值的方式。
使用字符串方法format:每个替换字段都用花括号括起,其中可能包含名称,还可能包含有关如何对相应的值进行转换和格式设置的信息。
>>>"{},{} and {}".format("first","second","third")
--->'first,second and third'
>>>"{0},{1} and {2}".format("first","second","third")
--->'first,second and third'
>>>"{3},{0},{2},{1},{3},{0}".format("be","not","or","to")
--->'to,be,or,not,to,be'
>>>from math import pi
>>>"{name} is approximately {value:.2f}.".format(value=pi,name="π")
--->'π is approximately 3.14.'
若变量与替换字段同名,还可简写:
>>>from math import e
>>>f"Euler's constant is roughly {e}."
--->"Euler's constant is roughly 2.718281828459045."
在格式字符串中,替换字段由几个部分组成,其中每个部分都是可选的:
字段名:索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段。
转换标志:跟在感叹号(!)后面的单个字符。当前支持的字符包括r(repr)、s(str)和a(ascii)。
格式说明符:跟在冒号(:)后面的表达式。格式说明符指定最终的格式,包括格式类型,字段宽度和数的精度,如何显示符号和千位分隔符,以及各种对齐和填充方式。
替换字段名:
向format提供要设置其格式的未命名参数,并在格式字符串中使用未命名字段,此时将按顺序将字段和参数配对:
>>>"{foo} {} {bar} {}".format(1,2,bar=4,foo=3)
--->'3 1 4 2'
通过索引来指定要在哪个字段中使用相应的未命名参数,这样可以不按顺序使用未命名参数:
>>>"{foo} {1} {bar} {0}".format(1,2,bar=4,foo=3)
--->'3 2 4 1'
>>>fullname=["alfred","smoketoomuch"]
>>>"Mr {name[1]}".format(name=fullname) --->'Mr smoketoomuch'
>>>import math
>>>tmpl="the {mod.__name__} module defines the value {mod.pi} for π"
>>>tmpl.format(mod=math)
--->'the math module defines the value 3.141592653589793 for π'
注:可以使用索引,句点表示法来访问导入的模块中的方法、属性、变量和函数
基本转换:
>>>print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
--->π 'π' '\u03c0'
注:上述三个标志r、s和a指定分别使用repr,str和ascii进行转换。
函数str通常创建外观普通的字符串版本(此处没有对输入的字符串做任何处理);函数repr尝试创建给定值的python表示(此处是一个字符串面量);函数ascii创建只包含ASCII字符的表示
字符串格式设置中的类型说明符:
b:将整数表示为二进制数
c:将整数解读为unicode码点
d:将整数视为十进制数进行处理(默认)
e:用科学表示法来表示小数(用e来表示指数)
E:与e相同,但用E来表示指数
f:将小数表示为定点数
F:与f相同,但对于特殊值(nan和inf),使用大写表示
g:自动在定点表示法和科学表示法作出选择
G:与g相同,但使用大写来表示指数和特殊值
n:与g相同,但插入随区域而异的数字分隔符
o:将整数表示为八进制数
s:保持字符串的格式不变,这是默认用于字符串的说明符
x:将整数表示为十六进制数并且使用小写字母
X:与x相同,但使用大写字母
%:将整数表示为百分数
>>>"the number is {num}".format(num=42) --->'the number is 42'
>>>"the number is {num:f}".format(num=42) --->'the number is 42.000000'
>>>"the number is {num:b}".format(num=42) --->'the number is 101010'
宽度,精度和千位分隔符
宽度:是使用整数指定的
>>>"{num:10}".format(num=3) --->' 3'
>>>"{num:10}".format(num="Bob") --->'Bob '
注:数和字符串的对齐方式不同。
精度:也是使用整数指定的,但要在前面加上一个表示小数点的句点。
>>>"pi day is {pi:.2f}".format(pi=pi) --->'pi day is 3.14'
>>>"pi day is {pi:10.2f}".format(pi=pi) --->'pi day is 3.14'
>>>"{:.5}".format("welcome to here") --->'welco'
符号,对齐和用0填充
要指定左对齐(<),右对齐(>),居中对齐(^)
可以使用填充字符来扩充对齐说明符,即使用指定字符(默认是空格)来填充:
>>>"{:$^15}".format("WIN GIB") --->'$$$$WIN GIB$$$$'
说明符=,用于指定将填充字符放在 符号和数字之间:
>>>print('{0:10.2f}\n{1:10.2f}'.format(pi,-pi))
3.14
-3.14
>>>print('{0:10.2f}\n{1:=10.2f}'.format(pi,-pi))
3.14
- 3.14
#:放在符号说明符和宽度之间,另一种转换方式:
>>>"{:b}".format(42) --->'101010'
>>>"{:#b}".format(42) --->'0b101010'
字符串方法:
1、center:在两边添加填充字符(默认是空格)让字符串居中
>>>"the middle by jimmy eat world".center(39)
--->' the middle by jimmy eat world '
>>>"the middle by jimmy eat world".center(39,"*")
--->'*****the middle by jimmy eat world*****'
2、find:在字符串查找子串:如果找到,就返回子串的第一个索引,否则返回-1
>>>"with a moo-moo here,and a moo-moo there".find("moo") --->7
>>>title="monty python's flying citcus"
>>>title.find("monty") --->0
>>>title.find('python') --->6
>>>title.find('flying') --->15
>>>title.find('zir') --->-1
还可以指定搜索的起点和终点(可选的):
>>>subject="$$$ get rich now!!! $$$"
>>>subject.find('$$$') --->0
>>>subject.find('$$$',1) (只指定了起点) --->20
>>>subject.find('!!!') --->16
>>>subject.find('!!!',0,16) (同时指定的起点和终点) --->-1
注:指定的搜索范围包含起点,但不包含终点
3、join:用于合并序列的元素,其作用与split相反
>>>seq=[1,2,3,4,5,6,7,8,9]
>>>a='+'
>>>seq.join(a) ---,出错,不能合并一个数字列表
>>>seq=["1","2","3","4","5","6","7","8","9"]
>>>a='+'
>>>a.join(seq) --->'1+2+3+4+5+6+7+8+9'
>>>dir = ' ','usr','bin','env'
>>>'/'.join(dir) --->' /usr/bin/env'
>>>print("C:" + "\\".join(dir)) --->C: \usr\bin\env
注:所合并的元素都必须是字符串
4、lower:返回字符串的小写版本
编写代码时若想忽略字符串的大小写:
>>>names=["gumby","smith","jones"]
>>>sty="Gumby"
>>>if sty.lower() in names: print("found it") --->found it
与lower相关的方法是title:将字符串转换为词首大写,即所有单词的首字母大写,其它字母都小写。
>>>"that's all folks".title() --->"That'S All Folks"
另一方法是使用模string中的函数capwords:
>>>import string
>>>string.capwords("that's all,folks") --->"That's All,folks"
另参考:islower,istitle,isupper,translate
5、replace:将指定的子串都替换为另一个字符串,并返回替换后的结果
>>>"This is test".replace('is','eez') --->'Theez eez test'
另参考:translate
6、split:用于将字符串拆分为序列
>>>"1+2+3+4+5+6+7+8+9".split("+") --->['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>>" /usr/bin/env".split('/') --->[' ', 'usr', 'bin', 'env']
>>>"using the default ".split() --->['using', 'the', 'default']
注:若没有指定分隔符,将默认的在单个或多个连续的空白字符(空格,制表符,换行符)处进行拆分。
7、strip:将字符串开头和末尾的空白(但不包括中间的空白)删除,并且返回删除后的结果
>>>" internal whitespace is kept ".strip() --->'internal whitespace is kept'
还可指定要删除哪些字符:
>>>"*** spam * for * everyone !!! ***".strip("*!") --->' spam * for * everyone !!! '
注:该方法只删除开头或末尾的指定字符串
8、translate:与replace一样替换字符串的特定部分,但translate只能进行单字符替换,优势在于能够同时替换多个字符
使用translate前必须创建一个转换表:这个转换表指出了不同unicode码点之间的转换关系。要创建转换表,可对字符串类型str调用方法maketrans,这个方法接受两个参数:两个长度相同的字符串,它们指定要将第一个字符串中的每个字符串都替换为第二个字符串中的相应字符。
>>>table=str.maketrans("cs","kz") ---将c替换为k,将s替换成z
>>>table --->{99: 107, 115: 122} ---看到的是unicode码点之间的映射
>>>"this is an incredible test".translate(table) --->'thiz iz an inkredible tezt'
调用方法maketrans时,还可以提供可选的第三个参数,指定要将哪些字母删除
>>>table=str.maketrans("cs","kz"," ") ---将所有的空格删除
>>>"this is an incredible test".translate(table) --->'thizizaninkredibletezt'
>>>table=str.maketrans("cs","kz","t") ---将所有字母t删除
>>>"this is an incredible test".translate(table) --->'hiz iz an inkredible ez'
9、判断字符串是否满足特定的条件
很多字符串方法都以is打头,如isspace,isdigit,isupper等,它们判断字符串是否具有特定性质(如包含的字符串全为空白,数字或大写)。如果字符串具备特定的性质,这些方法就返回True,否则返回False。
isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumetric、isprintable、isspace、istitle、isupper
posted @ 2018-08-06 21:08  Sky-wings  阅读(279)  评论(0编辑  收藏  举报