案例说明:
title = “Recipe 5: Rewriting an Immutable String”
要求对title进行以下操作:
- 移除:之前的子字符串;
- 将标点符号和空格替换为_,将所有字符转换为小写。
思路:
- 将字符串转换为列表,根据:的索引,利用切片删除:前的列表元素
- 逐元素将字符转换为小写
- 替换:后的子字符串中的空格和标点符号
要点:
本案例用到了string
模块。string
模块有两个重要的常量。
string.whitespace
列出了所有常用的空白字符,包括空格和制表符。string.punctuation
列出了常见的ASCII标点符号。Unicode拥有大量标点符号,可以根据区域设置来进行配置。
格式:str.join(sequence)
作用:将序列中的元素以指定的字符连接生成一个新的字符串。
代码:
In [1]: title = "Recipe 5: Rewriting an Immutable String"
In [2]: title_list = list(title)
In [3]: title_list
Out[3]:
['R',
'e',
'c',
'i',
'p',
'e',
' ',
'5',
':',
' ',
'R',
'e',
'w',
'r',
'i',
't',
'i',
'n',
'g',
' ',
'a',
'n',
' ',
'I',
'm',
'm',
'u',
't',
'a',
'b',
'l',
'e',
' ',
'S',
't',
'r',
'i',
'n',
'g']
In [4]: colon_position = title_list.index(':')
In [5]: del title_list[:colon_position+1]
In [6]: title_list
Out[6]:
[' ',
'R',
'e',
'w',
'r',
'i',
't',
'i',
'n',
'g',
' ',
'a',
'n',
' ',
'I',
'm',
'm',
'u',
't',
'a',
'b',
'l',
'e',
' ',
'S',
't',
'r',
'i',
'n',
'g']
In [7]: from string import whitespace, punctuation
In [8]: for position in range(len(title_list)):
...: if title_list[position] in whitespace+punctuation:
...: title_list[position]= '_'
...: else:
...: title_list[position]= title_list[position].lower()
...:
In [9]: title_list
Out[9]:
['_',
'r',
'e',
'w',
'r',
'i',
't',
'i',
'n',
'g',
'_',
'a',
'n',
'_',
'i',
'm',
'm',
'u',
't',
'a',
'b',
'l',
'e',
'_',
's',
't',
'r',
'i',
'n',
'g']
In [10]: title = ''.join(title_list)
In [11]: title
Out[11]: '_rewriting_an_immutable_string'