Python使用字符串

来源:互联网 发布:eclipse python import 编辑:程序博客网 时间:2024/06/06 14:26

1.基本字符串操作

所有标准序列的操作对字符串同样适用,上一张已经讲述了这些操作。一定要记住,字符串是不可变的。       

字符串的格式化参考

1.1传统C语言式

title = list('hello')name = 'world'print  ("%s,%s"% (title,name))
['h', 'e', 'l', 'l', 'o'],world

1.2命名参数

title = "world"year = 2013print ("hello %(titles)s, %(years)10d" % {"titles":title, "years":year})
hello world,       2013
#字典知识点在下面会有

"hello {title}, {year}".format(title=title, year=year)"hello {title}, {year}".format(**{"title":title, "year":year})
'hello world, 2013'
#string.format 也支持命名参数
string.format还有一个地方需要注意,如果参数是unicode,则string也必须是unicode,否则,会触发异常:
title = u"标题党""hello {0}".format(title)
'hello 标题党'
#

1.3位置参数


import datetime
title = "world"year = 2013print ("hello {0}, {1}".format(title, year))print ("today is {0:%Y-%m-%d}".format(datetime.datetime.now()))
hello world, 2013
today is 2017-11-13
#datetime参考此处

1.4字符串格式:%[(name)][flag][width][.][precision]type

name:可为空,数字(占位),命名(传递参数名,不能以数字开头)以字典格式映射格式化,其为键名

flag:标记格式限定符号,包含+-#0,+表示右对齐(会显示正负号),-左对齐,前面默认为填充空格(即默认右对齐),0表示填充0,#表示八进制时前面补充0,16进制数填充0x,二进制填充0b

width:宽度(最短长度,包含小数点,小于width时会填充)

precision:小数点后的位数,与C相同

type:输入格式类型,看下表

%% 百分号标记

%c 字符及其ASCII码

%s 字符串

%d 有符号整数(十进制)

%u 无符号整数(十进制)

%o 无符号整数(八进制)

%x 无符号整数(十六进制)

%X 无符号整数(十六进制大写字符)

%e 浮点数字(科学计数法)

%E 浮点数字(科学计数法,用E代替e)

%f 浮点数字(用小数点符号)

%g 浮点数字(根据值的大小采用%e或%f)

%G 浮点数字(类似于%g)

%p 指针(用十六进制打印值的内存地址)

%n 存储输出字符的数量放进参数列表的下一个变量


1.5模板字符串

string模块提供另外一种格式化的方法:
from string import Templates = Template('$x,glorious $x!')  #如果替换单词的一部分,那么x需要用花括号括起来 s=Template(make $$ selling ${x} again)s.substitute(x='slurm')           # $$ 插入$符号
'slurm,glorious slurm!'

除了关键字参数外,还可以使用字典变量提供值/名称对
s =Template('A $thing must never $action')d = {}d['thing'] = 'gentleman'd['action'] = 'show his socks'print (s.substitute(d))print (d)
A gentleman must never show his socks{'thing': 'gentleman', 'action': 'show his socks'}
#方法safe_subtitute不会因缺少值或者不正确使用$符号而出错

2.字符串方法

-find
find方法可以在一个较长的字符串中查找子串,它返回子串所在位置的最左端索引,如果没有找到就返回-1。这个方法还可以接受可选的起始点和结束点参数:
subject = 'wei suo yu wei'print (subject.find('wei'))print (subject.find('wei',1))
011
#也可以同时接受起始点和结束点
起始和终止的值指定的范围,一般都是包含第一个索引,但不包括第二个索引,这是Python的惯例
-join
这个相当于split方法的逆方法,用来连接序列中的元素
需要被连接的序列元素都必须是字符串
dirs = ['wang','luo','dan']'/'.join(dirs)
'wang/luo/dan'
-split
相当于join方法的逆方法
-strip
返回去除两侧(不包括内部)空格的字符串,也可以指定要去除的字符
a = '** dian deng  * '   #最后是一个空格a.strip('*')
' dian deng  * '
-replace
方法返回某字符串的所有匹配项军被替换之后得到字符串

-translate
与replace相似,不过translate只处理单个字符。在使用translate转换之前,需要先完成一张转换表,有点复杂,可以直接使用string模块里的maketrans。maketrans函数接受两个等长的参数(在python3中maketrans已经变成内建函数maketrans),表示第一个字符串中的每个字符都用第二个字符串中的相同位置的字符替换:
intab = "aeiou"outtab = "12345"trantab = str.maketrans(intab, outtab)str = "this is string example....wow!!!"print (str.translate(trantab))
th3s 3s str3ng 2x1mpl2....w4w!!!
translate有第二个可选参数,用来指定需要删除的字符,例如空格。但在Python3中做了改变
# 制作翻译表bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ') # 转换为大写,并删除字母oprint(b'runoob'.translate(bytes_tabtrans, b'o'))
b'RUNB'








原创粉丝点击