C语言使用函数printf()、sprintf()格式化输出结果,Python也提供了类似的功能。Python将若干值插入带有“%”标记的字符串中,从而可以动态地输出字符串。字符串的格式化语法如下所示。
"%s" % str1
"%s %s" % (str1, str2)
【代码说明】第1行代码使用一个值格式化字符串。第2行代码使用多个值格式化字符串,用于替换的值组成一个元组。
下面这段代码演示了字符串的格式化操作:
str1 = 'version'
num = 1.0
format = "%s" % str1
print(format)
format = "%s %d" % (str1, num)
print(format)
【代码说明】
注意 如果要格式化多个值,元组中元素的顺序必须和格式化字符串中替代符的顺序一致,否则,可能出现类型不匹配的问题。如果将上例中的%s和%d调换位置,将抛出如下异常:
TypeError: int argument required
使用%f可以格式化浮点数的精度,根据指定的精度做“四舍五入”。示例如下:
# 带精度的格式化
print ("浮点型数字: %f" % 1.25) # 以浮点数格式打印
print ("浮点型数字: %.1f" % 1.25) # 精确到小数点后1位
print ("浮点型数字: %.2f" % 1.254) # 精确到小数点后2位
【代码说明】
此外,Python还提供了对八进制、十六进制等数字进行格式化的替代符。下表列出了Python中格式化字符串的替代符及其含义。
前面使用了元素格式化多个值,也可以用字典格式化多个值,并指定格式化字符串的名称。下面这段代码说明了字典格式化字符串的用法。
#使用字典格式化字符串
print ("%(version)s: %(num).1f" % {"version": "version", "num": 2})
【代码说明】第2行代码定义了一个匿名字典,该字典中的两个value值分别对应字符串中的%(version)s和%(num).1f。输出结果:version:2.0
Python可以实现字符串的对齐操作,类似C语言中的“%[[+/-]n]s”。此外,还提供了字符串对齐的函数。
# 字符串对齐
word = "version3.0"
print (word.center(20))
print (word.center(20, "*"))
print (word.ljust(0))
print (word.rjust(20))
print ("%30s" % word)
【代码说明】
全部代码为:
计算机中存在可见字符与不可见字符。可见字符是指键盘上的字母、数字和符号。不可见字符是指换行、回车等字符,对于不可见字符可以使用转义字符来表示。Python中转义字符的用法和Java相同,都是使用“\”作为转义字符。
下面这段代码演示了转义字符的使用:
path = 'hello\tworld\n'
print(path)
print(len(path))
path = r'hello\tworld\n'
print(path)
print(len(path))
【代码说明】
注意 Python的制表符只占1个字符,而不是2个或4个字符
注意 如果要在字符串中输出“\”,需要使用“\”。
Python还提供了函数strip()、lstrip()、rstrip()去掉字符串中的转义符。
print('===================')
# strip()去掉转义字符
word = '\thello world\n'
print('直接输出:', word)
print('strip()后输出:', word.strip())
print('lstrip()后输出:', word.lstrip())
print('rstrip()后输出:', word.rstrip())
print('===================')
【代码说明】
与Java语言一样,Python使用“+”连接不同的字符串。Python会根据“+”两侧变量的类型,决定执行连接操作或加法运算。如果“+”两侧都是字符串类型,则进行连接操作;如果“+”两侧都是数字类型,则进行加法运算;如果“+”两侧是不同的类型,将抛出异常。
TypeError: cannot concatenate 'str' and 'int' objects
下面的代码演示了字符串的连接方法:
# 使用 + 链接字符串
print('========# 使用 + 链接字符串==============')
str1 = 'hello'
str2 = 'world'
str3 = 'hello'
str4 = 'china'
result = str1 + str2 + str3
print(result)
result += str4
print(result)
print('========================================')
【代码说明】
可见,使用“+”对多个字符串进行连接稍显烦琐。Python提供了函数join()连接字符串,join()配合列表实现多个字符串的连接十分方便。
代码实例如下:
# 使用join()连接字符串
print('==========# 使用join()连接字符串==========')
strs = ['hello', 'world', 'hello', 'china']
result = ''.join(strs)
print(result)
【代码说明】
reduce()的作用就是对某个变量进行累计。这里可以对字符串进行累计连接,从而实现多个字符串进行连接的功能。
代码实现如下:
# 使用reduce()连接字符串
print('=========# 使用reduce()连接字符串=========')
from functools import reduce
import operator
strs = ['hello', 'world', 'hello', 'china']
result = reduce(operator.add, strs, '')
print(result)
print('========================================')
【代码说明】
# 使用 + 链接字符串
print('========# 使用 + 链接字符串==============')
str1 = 'hello'
str2 = 'world'
str3 = 'hello'
str4 = 'china'
result = str1 + str2 + str3
print(result)
result += str4
print(result)
print('========================================')
# 使用join()连接字符串
print('==========# 使用join()连接字符串==========')
strs = ['hello', 'world', 'hello', 'china']
result = ''.join(strs)
print(result)
print('========================================')
# 使用reduce()连接字符串
print('=========# 使用reduce()连接字符串=========')
from functools import reduce
import operator
strs = ['hello', 'world', 'hello', 'china']
result = reduce(operator.add, strs, '')
print(result)
print('========================================')
字符串的截取是实际应用中经常使用的技术,被截取的部分称为“子串”。Java中使用函数substr()获取子串,C#使用函数substring()获取子串。而Python由于内置了序列,可以通过前面介绍的索引、切片获取子串,也可以使用函数split()来获取。字符串也属于序列。
下面这段代码使用序列的索引获取子串:
# 使用索引截取子串
print('----------# 使用索引截取子串---------')
word = 'world'
print(word[4])
【代码说明】第4行代码,访问字符串第5个字符的值。输出结果为“d”。
通过切片可以实现对字符串有规律的截取。切片的语法格式如下所示。
string[start : end : step]
【代码说明】其中string表示需要取子串的源字符串变量。[start:end:step]表示从string的第start个索引位置开始到第end个索引之间截取子串,截取的步长是step。即每次截取字符string[start+step],直到第end个索引。索引从0开始计数。
下面这段代码演示了使用切片截取子串的功能:
# 特殊切片截取子串
print('---------# 特殊切片截取子串----------')
str1 = 'hello world'
print(str1[0:3])
print(str1[::2])
print(str1[1::2])
str2 = 'ABCDEFG'
print(str2[:3])
print(str2[3:])
print(str2[::2])
print('-----------------------------------')
【代码说明】
如果要同时截取多个子串,可以使用函数split()实现。函数split()的声明如下所示。
split([char] [,num])
【代码说明】
代码如下:
# 使用split()获取子串
print('-----------# 使用split()获取子串-----')
sentence = "Tom said: a,b,c,d."
print('使用空格获取子串:', sentence.split())
print('使用逗号获取子串:', sentence.split(','))
print('使用逗号获取3个子串:', sentence.split(',', 2))
sentence1 = 'Uzi tell us : he is king and said : A, B, C, D.'
print('使用空格获取子串:', sentence1.split())
print('使用逗号获取子串:', sentence1.split(','))
print('使用空格获取4个子串:', sentence1.split(' ',3))
print('-----------------------------------')
【代码说明】
字符串连接后,Python将分配新的空间给连接后的字符串,源字符串保持不变。
# 字符串连接后,Python将分配新的空间给连接后的字符串,源字符串保持不变。
print('字符串连接后,Python将分配新的空间给连接后的字符串,源字符串保持不变。')
str3 = "a"
print(id(str3))
print(id(str3 + "b"))
print('-------------------------------------')
【代码说明】
Java使用equals()比较两个字符串的内容,Python直接使用“==”“!=”操作符比较两个字符串的内容。如果比较的两个变量的类型不相同,比较的内容也不相同。
下面这段代码演示了Python中字符串的比较:
# 字符串的比较
print('----------# 字符串的比较-------------')
str1 = 1
str2 = '1'
if str1 == str2:
print("相同")
else:
print("不相同")
if str(str1) == str2:
print("相同")
else:
print("不相同")
print('-------------------------------------')
【代码说明】
如果要比较字符串中的一部分内容,可以先截取子串,再使用“==”操作符进行比较。如果要比较字符串的开头或结尾部分,更方便的方法是使用startswith()或endswith()函数。
startswith()的声明如下所示。
startswith(substring, [,start [,end]])
【代码说明】
下面这段代码演示了startswith()和endswith()的使用。
# 比较字符串的开始和结束处
print('------# 比较字符串的开始和结束处---------')
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)))
print('-------------------------------------')
【代码说明】
注意 startswith()、endswith()相当于分片[0:n],n是源字符串中最后一个索引。startswith()、endswith()不能用于比较源字符串中任意一部分的子串。
字符串反转是指把字符串中最后一个字符移到字符串第一个位置,按照倒序的方式依次前移。Java中使用StringBuffer类处理字符串,并通过循环对字符串进行反转。
Python没有提供对字符串进行反转的函数,也没有类似charAt()这样的函数。但是可以使用列表和字符串索引来实现字符串的反转,并通过range()进行循环。
代码如下:
# 循环输出反转的字符串
def reverse(str):
out = ''
li = list(str)
for i in range(len(li), 0, -1):
out += ''.join(li[i-1])
return out
【代码说明】
不难发现,Python的实现代码更简短,而且更容易理解。用户还可以通过列表的reverse()函数实现字符串的反转,实现的代码将进一步简化。
# 使用list 的 reverse()
def reverse2(s):
li = list(s)
li.reverse()
s = ''.join(li)
return s
【代码说明】
Python的列表是对字符串进行处理的常用方式,灵活使用列表等内置数据结构处理字符串,能够简化编程的复杂度。利用序列的“切片”实现字符串的反转最为简洁,reverse()函数的主体只需要一行代码即可。
def reverse(s):
return s[::-1]
【代码说明】-1表示从字符串最后一个索引开始倒序排列。
ALL:
# 循环输出反转的字符串
def reverse(str):
out = ''
li = list(str)
for i in range(len(li), 0, -1):
out += ''.join(li[i-1])
return out
# 使用list 的 reverse()
def reverse2(s):
li = list(s)
li.reverse()
s = ''.join(li)
return s
if __name__ == '__main__':
print('手动实现:输出反转字符串:%s' % reverse('abcdef'))
print('列表方法:输出反转字符串:%s' % reverse('ABCDEF'))
Java中字符串的查找使用函数indexOf(),返回源字符串中第1次出现目标子串的索引。如果需要从右往左查找可以使用函数lastIndexOf()。Python也提供了类似功能的函数,函数find()与indexOf()的作用相同,rfind()与lastIndexOf()的作用相同。find()的声明如下所示。
find(substring [, start [ ,end]])
【代码说明】
rfind()的参数与find()相同,不同的是rfind()从字符串的尾部开始查找子串。
下面这段代码演示了find()、rfind()的使用:
# 查找字符串
sentence = "This is a apple."
print("find()方法实例:")
print(sentence.find("is", 3, 7))
print(sentence.find('a'))
print("rfind()方法实例:")
print(sentence.rfind('is', 3, 7))
print(sentence.rfind("a"))
【代码说明】
Java使用replaceFirst()、replaceAll()实现字符串的替换。replaceFirst()用于替换源字符串中第1次出现的子串,replaceAll()用于替换源字符串中所有出现的子串。这两个函数通过正则表达式来查找子串。而Python使用函数replace()实现字符串的替换,该函数可以指定替换的次数,相当于Java函数replaceFirst()和replaceAll()的合并。但是replace()不支持正则表达式的语法。
replace()的声明如下所示:
replace(old, new [, max])
【代码说明】
下面这段代码演示了replace()的使用:
# 字符串的替换
print('replace()方法实例:')
string = 'hello world, hello china. I love china.'
print(string.replace('he', 'HE'))
print(string.replace('he', 'HE', 3))
print(string.replace('he', 'HE', 1))
print(string.replace('ABC', 'abc'))
【代码说明】
注意 replace()先创建变量sentence的拷贝,然后在拷贝中替换字符串,并不会改变变量sentence的内容。
在开发中,经常把日期类型转换为字符串类型使用。字符串与日期的转换是工作中频繁遇到的问题。Java提供了SimpleDateFormat类实现日期到字符串的转换。Python提供了time模块处理日期和时间。
函数strftime()可以实现从时间到字符串的转换。strftime()的声明如下所示:
strftime(format[, tuple]) -> string
【代码说明】
字符串到时间的转换需要进行两次转换,需要使用time模块和datetime类,转换过程分为如下3个步骤。
1)调用函数strptime()把字符串转换为一个的元组,进行第1次转换。strptime()的声明如下所示。
strptime(string, format) -> struct_time
【代码说明】
datetime类的datetime()函数如下所示。
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
【代码说明】
下面这段代码演示了时间到字符串、字符串到时间的转换过程:
import time
import datetime
# 时间到字符串的转换
print("----------时间到字符串的转换-----------")
print(time.strftime("%Y-%m-%d %X", time.localtime()))
# 字符串到时间的转换
print("----------字符串到时间的转换-----------")
t = time.strptime("2017-12-25", "%Y-%m-%d")
y,m,d = t[0:3]
print(datetime.datetime(y, m, d))
【代码说明】
注意 格式化日期的特殊标记是区分大小写的,%Y与%y不相同。