Python基础之序列——字符串的使用

1.字符串的介绍

字符串在Python中可以看成由字符组成的序列。

2.字符串的基本操作

所有标准的序列操作(包括索引,切片,乘法,成员资格检查,最大值,最小值和长度)都适用于字符串,但是字符串是不可以变的,所以所有元素赋值和切片赋值都是非法

3.字符串的格式设置(简单版)
3.1 字符串格式设置符

类似于c语言中的经典格式输出函数printf,Python最开始使用最多的是字符串格式设置运算符——%
在%的左边指定一个格式字符串,并在右边指定要设置其格式的值。

>>> format = "hello %s, I'm %s"
>>> values = ("world","python")
>>> format % values
"hello world, I'm python"

上述格式字符串中的%s(s表示将值视为字符串)称为转换说明符号,指出要插的值在什么地方,相当于一个占位符。
在指定其设置格式的值的时候,可以使用单个的值(数字或者字符串),也可以使用元组(设置多个值的格式),甚至可以使用字典

3.2 模板字符串

类似于Unix Shell的语法,也可以向下面这样格式化字符串:

>>> from string import Template
>>> tmpl = Template("Hello,$what,I'm $who")
>>> tmpl.substitute(what = "world",who = "python")
"Hello,world,I'm python"

包含等号的参数称为关键字参数,可以将其视为一种像命名替换字段提供值的方式。

3.3 字符串方法format

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {}:来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。

>>> "hello {},I'm {}".format('world','python') #不设置顺序
"hello world,I'm python"
>>> '{3} {0} {2} {1} {3} {0}'.format('be','not','or','to') #设置顺序
'to be or not to be'
>>> "hello {what},I'm {who}".format(who = 'python',what = 'world') #设置命名字段
"hello world,I'm python"
4.字符串方法
方法描述
string.center(width [,fillchar])返回一个长度为max(len(string),width)的字符串。string居中,两端用fillchar填充(默认是空格)
string.ljust(width [,fillchar])返回一个长度为max(len(string),width)的字符串。string左对齐,末尾用fillchar填充(默认是空格)
string.rjust(width [,fillchar])返回一个长度为max(len(string),width)的字符串。string右对齐,开头用fillchar填充(默认是空格)
string.zfill(width)在字符串的左边填充0(但是将原来打头的+或-移到开头),使其长度为width
string.find(sub [,start [,end] ])返回在范围[start,end)内找到的第一个子串sub的索引,否则返回-1
string.join(sequence)用连接符string将sequence的所有字符串元素合并,并返回结果
string.split(sep)返回一个列表,包含以sep为分割符(默认为空格)对字符串进行划分的结果
string.replace(old,new [,max])将字符串中的子串old替换成new,并返回结果;最大替换次数为max
string.translate(table)按照转化表table中定义的字符转换规则,对字符串中的所有字符进行转换并返回结果
4.1 对齐方法

方法center通过在两边添加填充字符(默认为空格)让字符串居中
方法ljust通过在末尾添加填充字符(默认为空格)让字符串宽度为width
方法rjust通过在开头添加填充字符(默认为空格)让字符串宽度为width
方法zfill通过在开头添加填充字符**“0”**让字符串居中 ,宽度为width

>>> 'hello world'.center(18)
'   hello world    '
>>> 'hello world'.center(18,'*')
'***hello world****'
>>> 'hello'.rjust(8,'*')
'***hello'
>>> '123456'.zfill(8)
'00123456'
4.2 find

find在字符串中寻找子串,如果找到,就返回子串的第一个字符的索引,否则返回-1。

>>> "hello world,I'm python".find('python')
16
>>> "hello world,I'm python".find('c++')
-1

也可以指定搜索的起点个终点,在[起点,终点)这个范围内搜索

>>> "$ hello world,I'm python $".find('$',1) #只指定起点
25
>>> "$ hello world,I'm python $".find('$',1,25) #只指定终点
-1

其他常用方法:rfind,index,rindex,count,startwith、endwith

4.3 join

join作用与split相反,使用指定的连接符合并序列的元素,且所合并的元素必须都是字符串

>>> '+'.join('1')
'1'
>>> '+'.join('100') #字符序列
'1+0+0'
>>> '+'.join(['100','200'])
'100+200'
>>> seq = ['1','2','3','4']
>>> sep = '+'
>>> sep.join(seq)
'1+2+3+4'
>>> dirs = ['','usr','bin','env']
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print('c:' + '\\'.join(dirs))
c:\usr\bin\env

常用形式:separator.join(sequence)
用separator将sequence的所有字符串元素合并,并返回结果。

4.4 split

split和join的作用相反,使用指定的分割符,将字符串拆分成序列。

>>> '1+2+3+4'.split('+')
['1', '2', '3', '4']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
4.5 大小写转换
  • lower 返回字符串的小写版本
  • capitalize 返回字符串的副本,但是将第一个字符大写
  • swapcase 将字符串中的所有大小写反转,并返回结果
  • title 将字符串所有单词的首字母都大写,并返回结果
  • upper 返回字符串的大写版本
>>> 'hello'.lower()
'hello'
>>> 'hello'.upper()
'HELLO'
>>> 'hello world,I am python'.title()
'Hello World,I Am Python'
>>> 'hello world,I am python'.swapcase()
'HELLO WORLD,i AM PYTHON'
>>> 'hello world,I am python'.capitalize()
'Hello world,i am python'
4.6 replace

将指定的子串替换另一个子串,并返回替换后的结果。

>>> 'Where is my phone?'.replace('is','are')
'Where are my phone?'

类似的还有:translate

4.7 translate

translate和replace一样替换字符串中的特定部分,但不同的是它只能进行单个字符的替换,优势在于能够同时替换多个字符。
使用前用字符串类型str调用方法maketrans来创建一个转换表,指定不同的Unicode码点之间的转换关系。
该方法有两个参数:两个长度相同的字符串,将第一个字符串的每个字符都替换为第二个字符串中的相应字符,
和第三个可选参数:指定将哪些字母删除。

>>> table = str.maketrans('cs','kz')
>>> table
{115: 122, 99: 107}
>>> sen = 'this is an incredible test'
>>> sen.translate(table)
'thiz iz an inkredible tezt'
>>> table = str.maketrans('cs','kz',' ')
>>> sen = 'this is an incredible test'
>>> sen.translate(table)
'thizizaninkredibletezt'
4.8 strip

将字符开头和末尾的空白处(不包括中间的空白符)删除(也可以指定在两端删除的字符),并返回删除后的结果。

>>> '     hello,my freinds!    '.strip()
'hello,my freinds!'
>>> '**** hello,my freinds!!!!   '.strip(' !*')
'hello,my freinds'
4.9 判断字符串是否满足特定条件

判断多以is打头,如isspaceisdigitisupper,它们判断字符串是否有特定的性质(是否全为空白、数字或大写)。 若字符串具备这些性质,则返回True,否则返回False。
还有很多关于这种的:isalnum(都是字母或者数字)、isalpha(都是字母)、isdecimal(都是十进制数)、islower(都是小写字母)、isnumeric(都是数字字符)

参考文献

1.Beginning Python From Novice to Professional Third Edition. Magnus Lie Hetland
2.Python标准英文文档

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值