字符串是开发应用中常用的数据类型,字符串的处理是实际应用中经常面对的问题。正则表达式专门用于匹配应用中的数据,能够简化字符串的处理程序,python提供了模块匹配正则表达式。
- 字符串的格式化
- 字符串的截取、合并、过滤等操作
- 字符串的查找
- 正则表达式的语法
- python的正则表达式模块
一、字符串的格式化
python将若干值插入带有“%”标记的字符串中,从而可以动态地输出字符串。字符串的格式化语法为:
"%s"%str1
"%s %s"%(str1,str2)
第一行代码使用一个值格式化字符串,第二行代码使用多个值格式化字符串,用于替换的值组成一个元组。
#格式化字符串
str = "version"
num = 1.0
format = "%s"%str #用str的值替换字符串中的%s
print(format)
format = "%s %d"%(str,num) #用str,num分别替换字符串中的%s,%d的值
print(format)
运行结果:
version
version 1
注意:如果要格式化多个值,元组中元素的顺序必须和格式化字符串中替代符的顺序一致,否则,可能出现类型不匹配的问题,会抛出TypeError异常。
使用%f可以格式化浮点数的精度,根据指定的精度做“四舍五入”
#带精度的格式化
print("浮点型数字:%f"%1.25) #以浮点形式打印数字,默认情况下输出小数点后6位数字
print("浮点型数字:%1f"%1.25) #精确到小数点后1位
print("浮点型数字:%2f"%1.254) #精确到小数点后2位
运行结果:
浮点型数字:1.250000
浮点型数字:1.250000
浮点型数字:1.254000
python格式化字符串的替代符及其含义
%c 格式化字符及其ASCll码
%u 格式化无符号整型
%o 格式化无符号八进制数
%x 格式化无符号十六制数
%e 用科学计数法格式化浮点数
%g 根据值的大小决定使用%f还是%e
%p 用十六进制数格式化变量的地址
字符串格式化可以使用元素格式化,也可以使用字典格式化多个值。
#使用字典格式化字符串
print("%(version)s:%(num).1f"%{"version":"version","num":2})
python 可以实现字符串的对其操作,提供了字符串的对齐函数:
#字符串对齐
word = "version 3.0"
print(word.center(20)) #字符串居中,word两侧个输出5个空格,总共占20个字符
print(word.center(20,"*")) #字符串居中,word两侧个输出5个*,总共占20个字符
print(word.ljust(0)) #字符串左对齐
print(word.rjust(20)) #字符串右对齐,参数20表示一共输出20个字符,"version3.0"占10个字符,左边填充10个空格
print("%30s"%word) #表示先输出30个空格,再输出变量word
python中提供了strip(),lstrip(),rstrip()函数去掉字符串中的转义符:
path = "\thello word\n"
print(path)
print("strip:",path.strip()) #去除字符串的所有转义字符
print("lstrip:",path.lstrip()) #去除字符串左边的转义字符
print("rstrip:",path.rstrip()) #去除字符串右边的转义字符
运行结果:
hello word
strip: hello word
lstrip: hello word
rstrip: hello word
二、字符串的合并
python用“+”连接不同的字符串,python会根据“+”两侧变量的类型,决定执行连接操作或加法操作。如果两侧都是字符串,则执行连接操作,如果两侧都是数字,则执行加法操作,如果两侧是不同的类型,则抛出TypeError异常。
str1 = "hello "
str2 = "world "
str3 = "hello "
str4 = "china "
result = str1 + str2 + str3 #把str1,str2,str3的值连接起来,并把结果存放在result中
print(result)
result = result + str4
print(result)
python提供join()连接字符串,join()配合列表实现多个字符串的连接。
#join()函数实现列表元素的连接
list = ["hello ","world ","hello ","china "]
result = ''.join(list)
print(result)
join()函数,每次连接列表中的一个元素。
也可以利用reduce()函数进行字符串的累计连接:
#使用reduce()函数实现字符串连接
from functools import reduce
import operator #导入operator模块,利用add()函数实现累计连接
str = ["hello ","world ","hello ","china "]
print(reduce(operator.add,str,"")) #利用reduce()函数实现对空字符串的累计操作
运行结果:
hello world hello china
三、字符串的截取
字符串的截取是实际应用中经常使用的技术,被截取的部分成为子串,python内置了序列,可以通过索引、切片获取子串,也可以使用split()来获取。字符串也属于序列。
通过切片可以实现对字符串有规律的截取,切片的语法如下:
string[start:end:step]
其中string表示需要取子串的源字符串变量,[stsrt:end:step]表示从string的第start个索引位置开始到第end个索引之间截取子串,截取的步长是step。
str1 = "hello world"
print(str1[0:3]) #截取字符串中从第一个字符串到 第三个字符串之间的部分,不包含第三个字符串
print(str1[::2]) #切片省略了开始和结束字符,从字符串的第一个字符开始,以2位步长逐个截取字符
print(str1[1::2]) #切片中的数字1表示从字符串的第2个字符开始取字符,数字2表示以2位步长逐个截取字符
运行结果:
D:\Python36\python.exe E:/demo_py/python/char_6/str_split.py
hel
hlowrd
el ol
如果要同时截取多个子串,可以使用函数split()函数实现:
split([char] [,num])
参数char表示用于分割的字符,默认的分隔符是空格,参数num表示分割次数,如果num=2,将把源字符串分割为3个子串,默认情况下,将根据字符char在字符串中出现的个数来分割子串。函数的返回值是由子串组成的列表。
sentence = "bob said :1, 2, 3, 4"
print("以空格分割:",sentence.split())
print("以逗号分割:",sentence.split(','))
print("以逗号分割,分割次数为2次:",sentence.split(',',2))
运行结果:
以空格分割: ['bob', 'said', ':1,', '2,', '3,', '4']
以逗号分割: ['bob said :1', ' 2', ' 3', ' 4']
以逗号分割,分割次数为2次: ['bob said :1', ' 2', ' 3, 4']
四、字符串的比较
python直接使用“==”“!=”操作符比较两个字符串的内容,如果比较的两个变量的类型不相同,比较的内容也不相同。
str_1 = 1
str_2 = "1"
if(str_1==str_2):
print("两字符串相同")
else:
print("两字符串不同")
if(str(str_1)==str_2 ): #将数字1转换为字符类型与str_2比较则相同
print("两字符串相同")
else:
print("两字符串不同")
运行结果:
D:\Python36\python.exe E:/demo_py/python/char_6/str_cmp.py
两字符串不同
两字符串相同
如果要比较字符串中的一部分内容,可以现截取子串,在使用“==”操作符进行比较,如果要比较字符串的开头或结尾部分,更方便的是startswith()或ends()函数
startswith(substring,[,start[,end]])
参数substring是与源字符串开头部分比较的子串,参数start表示开始比较的位置,参数end表示比较结束的位置,如果字符串以substring开头,则返回True,否则,返回False.
word = "hello world"
print("hello"==word[0:5])
print(word.startswith("hello"))
print(word.endswith("ld",6))
print(word.endswith("ld",6,10))
print(word.endswith("ld",6,len(word)))
运行结果:
D:\Python36\python.exe E:/demo_py/python/char_6/startswith_endswith.py
True
True
True
False
True
五、字符串的反转
python没有提供对字符串进行反转的函数,但是可以使用列表和字符串索引来实现字符串的反转,并通过range()函数进行循环:
def reverse(s):
out = ""
l = list(s)
for i in range(len(l),0,-1):
out +=''.join(l[i-1])
print(out)
reverse("hellowprld")
运行结果:
D:\Python36\python.exe E:/demo_py/python/char_6/str_reverse.py
dlrpwolleh
实现字符串反转的另一种简洁方法:
def reverse(s):
return s[::-1]
print(reverse("helloporld"))
运行结果:
D:\Python36\python.exe E:/demo_py/python/char_6/str_reverse.py
dlropolleh
六、字符串的查找和替换
find(substring[,start[,end]])
str = "this is a apple"
print(str.find("a"))
print(str.rfind("a"))
运行结果:
D:\Python36\python.exe E:/demo_py/python/char_6/str_find.py
8
10
字符串的替换:
replace(old,new[,max])
参数old表示将被替换掉的字符串,参数new表示替换old的字符串,参数max表示使用new替换old的次数,函数返回一个新的字符串,如果子串old不在源字符串中,则函数返回源字符串的值。
str = "hello world,hello china"
print(str.replace("hello","hi"))
print(str.replace("hello","hi",1))
print(str.replace("hello","hi",2))
运行结果:
hi world,hi china
hi world,hello china
hi world,hi china
注意:replace()函数先创建变量str的拷贝,然后再拷贝中替换字符串,并不会改变变量str的内容。
七、字符串与日期的转换
在开发中,经常把日期类型转化为字符串类型使用,python中提供了time模块处理日期和时间,函数strftime()可以实现时间到字符串的转换:
strftime(format[,tuple])
import time,datetime
#时间到字符串的转换
print(time.strftime("%Y-%m-%d %X",time.localtime()))
#字符串到时间的转换
t = time.strptime('2008-08-08',"%Y-%m-%d")
y,m,d = t[0:3]
print(datetime.datetime(y,m,d))
运行结果:
D:\Python36\python.exe E:/demo_py/python/char_6/str_time.py
2017-11-17 01:00:22
2008-08-08 00:00:00