Python基础 第三章 使用字符串(3)字符串方法&本章小结

2023-07-29,,

字符串的方法非常之多,重点学习一些最有用的,完整的字符串方法参见《Python基础教程(第三版)》附录B。

模块string,虽然风头已小,但其包含了一些字符串方法中没有的常量和函数,故将模块string中几个非常有用的常量列出:

 string.digits: 包含数字0-9的字符串;
string.ascii_letters: 包含所有ASCII字母(大写和小写)的字符串;
string.ascii_lowercase: 包含所有小写ASCII字母的字符串;
string.printable: 包含所有可打印的ASCII字符的字符串;
string.punctuation: 包含所有ASCII标点字符的字符串;
string.ascii_uppercase: 包含所有大写ASCII字符的字符串。 # 虽然说的是ASCII字符,但实际上是未解码的Unicode字符串。

1. center

方法center通过在两边填充字符(默认空格)让字符居中。

其中数字参数为整个字符串的长度,包含填充符合。

 center = "The Middle by Jimmy Eat World".center()
print(center)
结果:
The Middle by Jimmy Eat World center = "The Middle by Jimmy Eat World".center(, "*")
print(center)
结果:
*****The Middle by Jimmy Eat World*****

2. find

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

 findstr = 'wiht a moo-moo here, and a moo-moo there'
print(findstr.find('moo'))
结果:7 title = "Monty Python's Flying Cirus"
print(title.find('Monty'))
结果:0 print(title.find('Python'))
结果:6 print(title.find('Flying'))
结果:15 print(title.find('Zirq'))
结果:-1

可指定搜索的起点和终点(第二个和第三个参数)

 subject = '$$$ Get rich now!!! $$$'
print(subject.find('$$$'))
# 只指定了起点
print(subject.find('$$$', 1))
结果:
0
20

起点和终点指定的搜索范围包含起点,但不包含终点(Python的惯常做法)。

 subject = '$$$ Get rich now!!! $$$'

 print(subject.find('!!!'))
# 同时指定了起点和终点
print(subject.find('!!!', 0, 16))
结果:
16
-1

 3. join (非常重要的字符串方法)

用于合并序列的元素,其作用与split相反。所合并序列的元素必须都是字符串。

 seq = ['','','','']
str = '+'
# 合并一个字符串列表,所合并列的元素都必须是字符串
print(str.join(seq))
结果:
1+2+3+4
 dirs = '','usr','bin','env'
print(dirs)
print('/'.join(dirs))
print('C:' + '\\'.join(dirs))
结果:
('', 'usr', 'bin', 'env')
/usr/bin/env
C:\usr\bin\env

4. lower - 该方法用于返回字符串的小写版本

 print('Tron Hamm Dance'.lower())
结果:
tron hamm dance
 name = 'Gumby'
names = ['gumby','smith','jones']
if name.lower() in names:
print('Found it!') 结果:
Found it!

5. replace - 该方法用于将指定子串都替换为另一个字符串,并返回替换后的结果

 newstr = 'This is a test'.replace('is', 'eez')
print(newstr)
结果:
Theez eez a test

6. split(非常重要的字符串方法)

用于将字符串分拆为序列,其作用与join相反。

如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符等)进行拆分。

 print('1+2+3+4'.split('+'))
# 如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符等)进行拆分
print('Using hte default'.split())
4 结果:
5 ['1', '2', '3', '4']
6 ['Using', 'hte', 'default']

7. strip - 该方法将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。

 str = '   internal whitespace is kept    '.strip()
print(str)
结果 :
internal whitespace is kept

还可在一个字符串参数中指定要删除哪些字符(同样只删除开头和末尾的指定字符)

 str = '*** SPAM * for * everyone!!! ***'
print(str.strip(' *!'))
结果:
SPAM * for * everyone

8. translate

方法translate与replace一样替换字符串的特定部分,但translate的优势在于能同时替换多个字符,效率更高。

使用translate前必须创建一个转换表(该表指出了不同Unicode码点之间的转换关系),对字符串类型str调用方法maketrans创建该转换表,这个方法接受两个参数(两个长度相同的字符串)。

 table = str.maketrans('cs', 'kz')
# 查看转换表内容
print("转换表内容:")
print(table)
sen = 'this is an incredible test'
print("替换结果:")
print(sen.translate(table)) >>>
转换表内容:
{99: 107, 115: 122}
替换结果:
thiz iz an inkredible tezt

调用maketrans时,还可提供可选的第三个参数,指定要将哪些字母删除。

 table = str.maketrans('cs', 'kz',' ')
# 查看转换表内容
print("转换表内容:")
print(table)
sen = 'this is an incredible test'
print("替换结果:")
print(sen.translate(table)) 结果:
转换表内容:
{99: 107, 115: 122, 32: None}
替换结果:
thizizaninkredibletezt

9. 判断字符串是否满足特定条件

以is打头的字符串方法,如isspace、isdigit和isupper,他们判断字符串是否具有特定性值,如果具备则返回True,否则返回False。

10. 本章小结

10.1 关键词:字符串格式设置、字符串方法。

10.2 本章新函数

 string.capwords(s[, sep]) #使用split根据sep拆分s,将每项的首字母大写,再以空格为分隔符将他们合并起来

 ascii(obj)  #创建指定对下的ASCII表示

Python基础 第三章 使用字符串(3)字符串方法&本章小结的相关教程结束。

《Python基础 第三章 使用字符串(3)字符串方法&本章小结.doc》

下载本文的Word格式文档,以方便收藏与打印。