第六章 字符串和正则表达式
字符串是开发程序中最常见的数据类型,字符串得到处理实际应用中经常面对的问题。Python
提供了功能强大的字符串模块,正则表达式专门用于匹配程序中的数据,能够简化字符串的处理程序。
6.1 常见的字符串操作
字符串是python
的一种基本类型,字符串的操作包括字符串的格式化,字符串的截取,过滤,合并和查找等操作。
使用%f
可以格式浮点数的精度,根据指定的精度做四舍五入。
#带精度的格式化
print ("浮点型数字: %f" % 1.25) #以浮点数格式打印
print ("浮点型数字: %.1f" % 1.25) #精确到小数点后一位
print ("浮点型数字: %.2f" % 1.254) #精确到小数点后两位
如果要在字符串中输入%
,需要使用%%
。Python
可以实现字符串的对齐操作。
#字符串对齐
word = "version3.0"
print (word.center(20))
print (word.center(20, "*"))
print (word.ljust(20))
print (word.rjust(20))
print ("%30s" % word)
代码中的“20”表示一共输出20个字符。ljust
表示左对齐,rjust
表示右对齐。%30s
表示先输出30个空格。python
使用\
作为转义字符。
# 输出转义字符
path = "hello\tworld\n"
print (path)
print (len(path))
path = r"hello\tworld\n"
print (path)
print (len(path))
Python
还提供了函数strip()
,lstrip()
,rstrip()
,去掉转义字符串中的转义符。
# strip()去掉转义字符
word = "\thello world\n"
print ("直接输出:", word)
print ("strip()后输出:", word.strip())
print ("lstrip()后输出:", word.lstrip())
print ("rstrip()后输出:", word.rstrip())
python
使用“+
”连接不同的字符串。python
会根据“+
”两侧变量的类型,决定执行连接操作或是加法运算。如果两侧为字符串类型,则进行连接操作;如果两侧都是数字类型,则进行加法运算;如果两侧是不同的类型,将抛出异常。
# 使用"+"连接字符串
str1 = "hello "
str2 = "world "
str3 = "hello "
str4 = "China "
result = str1 + str2 + str3
result += str4
print (result)
python
提供了函数join()
连接字符串,配合列表可以实现多个字符串的连接。
# 使用join()连接字符串
strs = ["hello ", "world ", "hello ", "China "]
result = "".join(strs)
print (result)
字符串的截取是实际应用中最常用的技术,被截取的部分称为“子串”。如果同时截取多个子串,可以使用函数split()
实现。
split ([char] [,num])
参数char
表示用于分割的字符(变量名),默认的分割字符是空格。参数num
表示分割的次数。如果num
等于2,将把源字符串分割为3个子串。字符串连接后,python
将分割新的空间给连接后的字符串,源字符串保持不变。
# 使用split()获取子串
sentence = "Bob said: 1, 2, 3, 4"
print ("使用空格取子串:", sentence.split())
print ("使用逗号取子串:", sentence.split(","))
print ("使用两个逗号取子串:", sentence.split(",", 2))
python使用“==
”“!=
”操作符比较两个字符串的内容,如果比较的两个变量的类型不同,比较的内容也不相同。
# 字符串的比较
str1 = 1
str2 = "1"
if str1 == str2:
print ("相同")
else:
print ("不相同")
if str(str1) == str2:
print ("相同")
else:
print ("不相同")
如果比较字符串中的一部分内容,可以先截取子串,再使用“==
”操作符进行比较,如果要比较字符串的开头或结尾部分,更方便的方法是使用startwith()
或endwith()
函数。
# 比较字符串的开始和结束处
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)))
字符串反转是把字符串最后一个字符移到字符串第一个位置按照倒序的方式依次前移。例如:
#函数反转
def reverse(s):
out = ""
li = list(s)
for i in range(len(li), 0, -1):
out += "".join(li[i-1])
return out
print (reverse("hello"))
上边的代码就实现了字符串的反转。代码还可以进一步简化:
#简化函数反转
def recerse(s):
li = list(s)
li.reverse()
s = "".join(li)
return s
print (reverse("hello"))
python
的列表是对字符串进行处理的常用方式,灵活使用列表等内置数据结构处理字符串,能够简化编程的复杂度。reverse()
函数的主体只需要一行代码即可。
python
提供了查找字符串的功能。find()
的声明如下:
find(substring [, start [,end]])
参数substring
表示待查找的字符串,参数start
表示开始搜索的索引位置,参数end
表示结束搜索的索引位置,即在分片[start:end]
中查找。
rfind()
的参数与find()
相同,不同的是rfind()
从字符串的尾部开始查找子串。
# 查找字符串
sentence = "This is a apple."
print (sentence.find("a"))
sentence = "This is a apple."
print (sentence.rfind("a"))
运行结果:
8
10
python
使用函数replace()
实现字符串的替换,该函数可以指定替换的次数,声明如下:
replace(old, new [, max])
参数old
表示将被替换的字符串,参数new
表示替换old
字符串,参数max
表示使用new
替换old
的次数。
# 字符串的替换
centence = "hello world, hello China"
print (centence.replace("hello", "hi"))
print (centence.replace("hello", "hi", 1))
print (centence.replace("abc", "hi"))
运行结果:
hi world, hi China
hi world, hello China
hello world, hello China
在开发中,经常把日期类型转换为字符串类型使用,字符串与日期的在转换是工作中频繁遇到的问题。python
提供了time
模块处理日期和时间。函数strftime()
可以实现从时间到字符串的转换。strftime()
声明如下:
strftime(format[, tuple])
参数format
表示格式化日期的特殊字符,例如“%Y-%m-%d
”。参数tuple
表示需要转换的时间,用元组储存。元组中的元素分别表示年,月,日,时,分,秒。
字符串到时间的转换需要进行两次转换,需要使用time
模块和datetime
类。下面这段代码展示了时间到字符串,字符串到时间的转换过程。
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))
函数localtime()
返回当前的时间,strftime()
把当前的时间转换为字符串类型。