《Modern Python Cookbook》(Python经典实例)笔记1.9 通过字符列表创建复杂的字符串

博客以 'Recipe 5: Rewriting an Immutable String' 为例,介绍Python字符串处理操作。思路是将字符串转列表,按索引切片删除特定元素,字符转小写,替换空格和标点。还提及相关模块及常量,最后介绍了连接序列元素生成新字符串的格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

案例说明:
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'
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值