#python 系列# —2 字符串

概述

上一篇文章讲完了列表和元组两种序列类型,也讲了一些序列基本的操作。这一篇文章我们来讲讲字符串
相信有过编程经验的童鞋都很熟悉字符串类型。那么python的字符串又有什么不一样呢?


字符串

字符串作为序列类型之一,所以具有序列的基础特效,这一点在上一篇文章已经讲到了,不再重复提。
由于字符串的操作函数太多了,这里我们只讲一些基本和重要的操作。

字符串格式化

字符串的格式化用符号 % 实现。% 号左边放置的是格式化字符串,右边放置的希望被格式化的值。
我们来看一下简单的格式化操作

1
2
3
4
5
6
7
## 字符串 格式化##
from math import pi
formatStr='hello, %s'
print(formatStr % 'python')#==>hello, python
formatStr='pi values is %.3f'
print(formatStr % pi) #==> pi values is 3.142
print('%010.3f' % pi) #==> 000003.142

比较完整的格式化规则

  • %c 转换成字符(ASCII 码值,或者长度为一的字符串)
  • %r 优先用repr()函数进行字符串转换
  • %s 优先用str()函数进行字符串转换
  • %d 转成有符号十进制数
  • %u 转成无符号十进制数
  • %o 转成无符号八进制数
  • %x/%X 转成无符号十六进制数(x / X 代表转换后的十六进制字符的大小写)
  • %e/%E 转成科学计数法(e / E控制输出e / E)
  • %f/%F 转成浮点数(小数部分自然截断)
  • %g/%G %e和%f/%E和%F的简写
  • %% 输出%(格式化字符串里面包括百分号,那么必须使用%%)

字符串函数 –find

find函数可以匹配单个字符或者字符串子串,并返回索引。

1
2
3
4
5
6
7
## 字符串函数 -- find##
strValue='Hi man'
index = strValue.find('m')
print(index)## ==>3
## find还可以接受起点和终点##
index = strValue.find('m',4,6)##找不到所以返回 -1
print(index)

字符串函数 –split和join

split和join是一对反操作函数,所以放在一起讲,split可以根据一个字符分割字符串,
join是讲字符串列表里面的元素加上一个连接字符进行连接。

1
2
3
4
5
6
7
8
#字符串函数 -- split##
strValue='h+e+l+l+o';
strList = strValue.split('+')
print(strList)##字符串序列 ==>['h', 'e', 'l', 'l', 'o']
## 字符串函数 -- join##
## join函数和split函数是相反的两个函数 ##
strValue = '+'.join(strList)
print(strValue) ##==>h+e+l+l+o

字符串函数 – lower和upper

lower可以将字符串按小写输出,upper则相反,按大写输出。

1
2
3
4
5
## 字符串函数 -- lower ##
strVale = 'Hello World'
print(strVale.lower()) #==>hello world
## 字符串函数Upper##
print(strVale.upper())#==>HELLO WORLD

字符串函数 – strip

strip 函数可以将字符串两边的空格去除。

1
2
3
## 字符串函数 -- strip##
strValue=' 11dd '
print(strValue.strip()) #==>11dd

字符串函数 – replace

replace 函数可以替换单个字符或者字符串子串

1
2
3
## 字符串函数 --replace ##
strValue = 'hello java'
print(strValue.replace('java', 'python'))## ==>hello python

字符串函数 – translate

translate 函数跟replace相似,只不过translate只可以按一个字符进行替换,而不是一个子串,
但是却可以一次进行多个的一个字符。

1
2
3
4
## 字符串函数 -- translate ##
strValue = 'hello python'
table=strValue.maketrans('eo','bc')
print(strValue.translate(table))##==>hbllc pythcn


总结

这一篇我们稍微讲了字符串的一些基本应用,后面我们会将另外一种数据结构 – 字典。

如果看的爽,不如请我吃根辣条?